我正在使用ngx-translate来翻译我的Angular Web应用程序,似乎ngx-translate在函数getTranslation(language)上有一个问题。当它被调用时,它会改变当前的语言吗?暂时的?然后我的组件就不会以正确的语言显示。
export class InputRadioComponent extends FormComponentInput implements OnInit {
constructor(protected formDynamicS) {
}
public ngOnInit() {
this.translate.getTranslation("fr").subscribe(res => {
this.choose["fr"] = res['form-component']['choose-answer'];
});
this.translate.getTranslation("en").subscribe(res => {
this.choose["en"] = res['form-component']['choose-answer'];
});
this.translate.getTranslation("de").subscribe(res => {
this.choose["de"] = res['form-component']['choose-answer'];
});
}
}在这种情况下,就像this.translate.getTranslation("de")是最后一个调用一样,我的组件总是以德语显示。我找到了一个变通方法,但我不想在代码中保留它。以下是我的解决方法:
let languages: string[] = ["fr", "en", "de"];
languages.splice(languages.indexOf(this.translate.currentLang));
languages.push(this.translate.currentLang);
languages.forEach((language) => {
this.translate.getTranslation(language).subscribe(res => {
this.choose[language] = res['form-component']['choose-answer'];
});
});它允许我保留currentLang,因为它将是getTranslation的最后一个调用
发布于 2019-03-19 12:14:11
我刚才也遇到了同样的问题。我不得不使用cloneDeep (lodash方法)来解决这个问题。
const translateDeepCopy = cloneDeep(this.translate);
translateDeepCopy.getTranslation(lang).subscribe(res => {
});
发布于 2018-06-06 02:24:53
我同意,这是一种相当奇怪的行为。但是参考你的解决方法,你可以有一个更容易的解决方案来重置语言。
只要打个电话
this.translate.use('<LANGUAGE>');例如:
this.translate.getTranslation("de").subscribe(res => {
this.choose["de"] = res['form-component']['choose-answer'];
this.translate.use('en');
});发布于 2019-03-08 12:50:05
为什么不在启动时加载每个翻译文件,并在服务中保留一个引用?这并不理想,但如果您的翻译文件相对较小,并且您没有那么多语言要处理,那么这可能是一个很好的权衡。
奇怪的是,我在我的代码中调用了getTranslation,它不会改变语言,而translate.use显然会改变语言。
https://stackoverflow.com/questions/50706158
复制相似问题