ngx-translate .instant返回键而不是值 [英] ngx-translate .instant returns key instead of value

查看:464
本文介绍了ngx-translate .instant返回键而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一种方法,该方法可以接受字符串键并通过使用translate.instant(parameter)返回翻译后的字符串值.问题是它返回键(参数).通常,如果找不到翻译,则将其返回.我认为问题在于加载程序加载翻译之前会调用该方法.

I am trying to make a method which would accept string key and return translated string value by using translate.instant(parameter). The problem is that it returns key(parameter). Usually this is returned if it doesn't find translation. I think the problem is that method gets called before loader loads translations.

我的app.module.ts导入:

My app.module.ts imports:

    TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: (createTranslateLoader),
    deps: [HttpClient]
  }
})

createTranslateLoader函数:

createTranslateLoader function:

    export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

在我的app.component中:

In my app.component:

constructor(public translate: TranslateService){
   translate.setDefaultLang('en');
   translate.use('en');
}

当我使用管道翻译html时,效果很好.

When I translate in html using pipes it works ok.

推荐答案

您正在使用TranslateHttpLoader,它会在请求翻译时发出HTTP请求-translate.use('en').如果在HTTP调用返回之前调用instant(messageKey)方法,则ngx-translate将返回键,因为它尚无翻译.因此,您应该使用get(messageKey)方法获取翻译-它是异步的并返回Observable:

You are using the TranslateHttpLoader which makes an HTTP request when it's asked for translations - translate.use('en'). If you call the instant(messageKey) method before the HTTP call returns, ngx-translate will return the key, since it has no translations yet. So you should use the get(messageKey) method to get the translation - it's asynchronous and returns an Observable:

this.translateService.get('hello.world').subscribe((translated: string) => {
    console.log(res);
    //=> 'Hello world'

    // You can call instant() here
    const translation = this.translateService.instant('something.else');
    //=> 'Something else'
});

仅当您确定翻译已被加载时才可以使用instant方法(如代码示例中所示),或者您可以编写自定义同步翻译加载器并在任何地方使用instant.

You can use the instant method only when you are sure that the translations have been already loaded (as in the code example) or you can write your custom synchronous translation loader and use instant anywhere.

这篇关于ngx-translate .instant返回键而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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