简体   繁体   English

在 ts 文件上使用动态文本进行 ngx-translate

[英]ngx-translate with dynamic text on ts file

I'm using ngx-translate for internationalization on Ionic 3 app.我在Ionic 3应用程序上使用ngx-translate进行国际化。 I have used pipe nicely on HTML code.我在HTML代码上很好地使用了pipe But now I have a situation like below on ts file.但是现在我在ts文件上遇到了如下情况。 Can you tell me how to handle such dynamic use case with ngx ?你能告诉我如何用ngx处理这种动态用例吗?

 updateApi(topic) {
     this.showToast(`Topic ${topic.name} subscribed!`);//this is the dynamic text
  }

 showToast(message) {
        let toast = this.toastCtrl.create({
            message: message,
            duration: 3000
        });
        toast.present();
    }

The problem here is I don't know the value of ${topic.name} up front.这里的问题是我不知道${topic.name}的价值。 So how can I give the key/value for that on i18n json file?那么如何在i18n json文件中给出key/value呢? or am I missing something here?还是我在这里遗漏了什么?

You have to inject the Translate Service in your component :您必须在组件中注入翻译服务:

constructor(private translate: TranslateService) {}

And declare in your translation file something like this :并在您的翻译文件中声明如下:

{
  "TOPIC": "Topic {{value}} subscribed!"
}

Then you can choose one of the following way :然后您可以选择以下方式之一:

Translate instantly :立即翻译:

showToast(this.translate.instant('TOPIC', {value: topic.name}));

Translate with an observable用 observable 翻译

this.translate.get('TOPIC', {value: topic.name}).subscribe(res => {
      showToast(res);
});

Translate directly in the template直接在模板中翻译

{{ 'TOPIC' | translate: {value: topic.name} }}

你也可以这样做:

this.showToast(this.translate.instant('TOPIC', {value: ${topic.name}}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM