ngx-translate 与 ts 文件上的动态文本
ngx-translate with dynamic text on ts file
我在 Ionic 3
应用程序上使用 ngx-translate 进行国际化。我在 HTML
代码中很好地使用了 pipe
。但是现在我在 ts
文件上遇到了如下情况。你能告诉我如何用 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
呢?还是我在这里遗漏了什么?
您必须在您的组件中注入翻译服务:
constructor(private translate: TranslateService) {}
并在您的翻译文件中声明如下:
{
"TOPIC": "Topic {{value}} subscribed!"
}
那么您可以选择以下方式之一:
即时翻译:
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} }}
你也可以这样操作:
this.showToast(this.translate.instant('TOPIC', {value: ${topic.name}}));
我在 Ionic 3
应用程序上使用 ngx-translate 进行国际化。我在 HTML
代码中很好地使用了 pipe
。但是现在我在 ts
文件上遇到了如下情况。你能告诉我如何用 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
呢?还是我在这里遗漏了什么?
您必须在您的组件中注入翻译服务:
constructor(private translate: TranslateService) {}
并在您的翻译文件中声明如下:
{
"TOPIC": "Topic {{value}} subscribed!"
}
那么您可以选择以下方式之一:
即时翻译:
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} }}
你也可以这样操作:
this.showToast(this.translate.instant('TOPIC', {value: ${topic.name}}));