无法使用ngx-translate的service-translate.get翻译文本 [英] Unable to translate text using ngx-translate's service-translate.get

查看:443
本文介绍了无法使用ngx-translate的service-translate.get翻译文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用翻译管道来翻译文本,但是目前正在努力使用翻译服务的get和Instant方法加载翻译. 下面是我在app.component.ts

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?

推荐答案

get将只执行一次,并使用当前使用的语言获取键的值.您需要按如下所示将控制台日志绑定到语言更改事件:

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));

对于最新版本(^ 7.0.0),使用stream方法还有另一种方法:

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));

这与get基本上相同,但是支持语言更改(每次更改所选语言时都会发出新值).

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

这篇关于无法使用ngx-translate的service-translate.get翻译文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆