嘿伙计我在翻译ts文件中的文本时遇到问题,例如使用ng-2翻译警报和弹出窗口。我已经完成了HTML的翻译,这非常简单,但我现在被卡住了,比方说,我的代码是这样的:
showAlert() {
let alert = this.alertCtrl.create({
title: 'Confirmed',
subTitle: this.ride.type == "rider" ? 'Your ride request has been created.' : 'Your ride offer has been created.',
buttons: [{
text: 'Ok',
handler: () => {
alert.dismiss()
.then(()=>{
this.navCtrl.pop();
})
return false;
}
}]
});
alert.present();
}
}
如何翻译标题和副标题?我已经在json文件中有键和相应的翻译文本,但我不知道如何在语法上这样做。在html文件中它只是{{KEY |翻译}}但不确定它会在这里。任何帮助将不胜感激,谢谢!!
答案 0 :(得分:2)
您需要使用TranslateService。 你有两种方法:即时和获取。 我个人总是使用即时,因为我100%确定我的翻译文件已加载。 我用get写了一个例子,但它可能是错误的(没有经过测试)。
import { TranslateService } from "ng2-translate";
constructor(
protected translateService: TranslateService
) {
}
/* instant(key: string|Array<string>, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead. */
showAlert() {
let alert = this.alertCtrl.create({
title: this.translateService.instant('KEY'),
subTitle: this.ride.type == "rider" ? this.translateService.instant('KEY2') : this.translateService.instant('KEY3')
});
}
/* otherwise */
showAlert() {
this.translateService.get('KEY')
.flatMap((trad) => {
let key;
if (this.ride.type == "rider") {
key = 'KEY2';
} else {
key = 'KEY3';
}
return this.translateService.get(key).map((trad2) => {
return { trad: trad, trad2: trad2 };
});
})
.subscribe((trads: { trad: string, trad2: string }) => {
let alert = this.alertCtrl.create({
title: this.translateService.instant(trads.trad),
subTitle: trads.trad2
});
},
(error) => {
// ERROR HERE (SUBSCRIBE NOT CALLED)
});
}
答案 1 :(得分:0)
您可以在控制器中注入 TranslateService ,然后使用 get 方法获取已翻译的字符串。
get(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>
您可以在组件中查看方法以获取值。请记住,它直接返回一个可观察的而不是翻译的值。