Angular ngx-translate getTranslation问题

时间:2018-06-05 17:51:50

标签: angular ngx-translate

我正在使用ngx-translate翻译我的Angular Web-app,似乎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的最后一次调用

4 个答案:

答案 0 :(得分:1)

我同意,这是一种相当奇怪的行为。但是,参考您的解决方法,您可以更轻松地重置语言。

只需致电

this.translate.use('<LANGUAGE>');

e.g。

this.translate.getTranslation("de").subscribe(res => {
  this.choose["de"] = res['form-component']['choose-answer'];
  this.translate.use('en');
});

答案 1 :(得分:0)

为什么不在启动时加载每个翻译文件并在服务中保留引用?这不是理想的选择,但是如果您的翻译文件相对较小并且您没有太多语言可以处理,那么这可能是一个不错的权衡。

奇怪的是,我确实从我的代码中调用了getTranslation,并且在translate.use显然不会改变语言的情况下。

答案 2 :(得分:0)

我刚才遇到了同样的问题。我不得不使用cloneDeep(lodash方法)来解决问题。

const translateDeepCopy = cloneDeep(this.translate);

translateDeepCopy.getTranslation(lang).subscribe(res => {
  
});

答案 3 :(得分:0)

我可以建议您在这种情况下使用Transloco,它不会受到上述行为的影响,甚至更易于使用。

在Transloco getTranslation中,就像:

const translation = this.translate.getTranslation("fr");
this.choose["fr"] = translation['form-component']['choose-answer'];