我正在使用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
的最后一次调用
我同意,这是一种相当奇怪的行为。但是,参考您的解决方法,您可以更轻松地重置语言。
只是打电话
this.translate.use('<LANGUAGE>');
EG
this.translate.getTranslation("de").subscribe(res => {
this.choose["de"] = res['form-component']['choose-answer'];
this.translate.use('en');
});
为什么不在启动时加载每个转换文件并在服务中保留引用?这并不理想,但如果您的翻译文件相对较小而且您没有那么多语言可以处理,那么这可能是一个很好的权衡。
奇怪的是,我确实从我的代码中调用了getTranslation,而且它并没有改变语言,而translate.use显然是这样。
我刚才遇到了同样的问题。我不得不使用cloneDeep(lodash方法)来解决问题。
const translateDeepCopy = cloneDeep(this.translate);
translateDeepCopy.getTranslation(lang).subscribe(res => {
});