【问题标题】:Need help translating text in my ts files需要帮助翻译我的 ts 文件中的文本
【发布时间】:2017-03-22 16:54:58
【问题描述】:

大家好,我在使用 ng-2 translate 翻译 ts 文件中的文本(如警报和弹出窗口)时遇到问题。我已经完成了 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 |翻译}} 但不确定它会在这里。任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: angular typescript ionic2


    【解决方案1】:

    您需要使用 TranslateService。 你有两种方法:instant 和 get。 就我个人而言,我总是使用即时,因为我 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)
        });
    }
    

    【讨论】:

    • 像魅力一样工作。非常感谢! :)
    【解决方案2】:

    您可以在控制器中注入 TranslateService,然后使用 get 方法获取翻译后的字符串。

    get(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>
    

    你可以在组件中查看获取值的方法。请记住,尽管它直接返回一个 observable 而不是翻译后的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-16
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2023-03-31
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多