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

我是研究僧i 提交于 2019-12-11 04:39:33

问题


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



来源:https://stackoverflow.com/questions/45231037/unable-to-translate-text-using-ngx-translates-service-translate-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!