ngx-translate 与 ts 文件上的动态文本 [英] ngx-translate with dynamic text on ts file

查看:19
本文介绍了ngx-translate 与 ts 文件上的动态文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ngx-translate 用于 Ionic 3 应用程序的国际化.我在 HTML 代码上很好地使用了 pipe.但是现在我在 ts 文件上遇到了如下情况.你能告诉我如何用 ngx 处理这种动态用例吗?

I'm using ngx-translate for internationalization on Ionic 3 app. I have used pipe nicely on HTML code. But now I have a situation like below on ts file. Can you tell me how to handle such dynamic use case with 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();
    }

这里的问题是我不知道 ${topic.name} 的值.那么如何在 i18n json 文件上给出 key/value 呢?还是我在这里遗漏了什么?

The problem here is I don't know the value of ${topic.name} up front. So how can I give the key/value for that on i18n json file? 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 :

立即翻译:

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

用 observable 翻译

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

直接在模板中翻译

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

这篇关于ngx-translate 与 ts 文件上的动态文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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