Unable to translate text using ngx-translate's service-translate.get
Asked Answered
F

2

1

I am able to translate text using translate pipe but currently struggling to load translations using translate service's get and instant method. Below is my code in app.component.ts

export class AppComponent {

event : string;
constructor(private translate: TranslateService) {
    translate.addLangs(["en", "fr"]);
    translate.setDefaultLang('en');
    let LangChangeEvent : {}
    let browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');

    this.translate.get('ALL_LOCATIONS_TREEVIEW').subscribe((event: String) => {
              console.log(event);

          });
}

}  

I am printing event in the console. I want its translation to change whenever user changes language. My rest of translations (using pipe) are working fine, but i can't see change in console with change in language. What am i missing?

Fungistat answered 21/7, 2017 at 6:58 Comment(0)
U
7

get will only execute once and will get the value of the key with the currently used language. You need to bind the console log to the language change event as follows:

this.translate.onLangChange
.mergeMap(() => this.translate.get('ALL_LOCATIONS_TREEVIEW'))
.subscribe(v => console.log(v));

With the newest relase (^7.0.0) there is another way to do this, using the stream method:

 this.translate
.stream('ALL_LOCATIONS_TREEVIEW')
.subscribe(v => console.log(v));

This is basically the same as get, but language change aware (emits a new value every time the selected language is changed).

For more information take a look at the documentation

Underwaist answered 21/7, 2017 at 9:50 Comment(2)
worked like a charm. I wanted to know is there any other way than using subscribe on .stream or .get as in angular-translate it was more simple like this.$translate.instant(key).Fungistat
the instant method is part of the API too, but I cant tell if its going to be language change aware, as I havent used itUnderwaist
E
0

Simple way to do that:

this.translate.instant('string_key_from_json');
Excellent answered 7/9, 2020 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.