Unable to translate text using ngx-translate's

2019-07-28 20:34发布

问题:

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?

回答1:

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