Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngx-translate getTranslation issue

I am using ngx-translate to translate my Angular Web-app, and it seems that ngx-translate has an issue with the function getTranslation(language). When it's called, it changes the current language ?temporarly? and then my component is not displayed in the right 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'];
    });
  }
}

In this case, like this.translate.getTranslation("de") is the last call, my component is always displayed in german. I find a workaround but it's not something I want to keep on my code. Here is my workaround :

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'];
  });
});

It allows me to keep the currentLang, because it will be the last call by getTranslation

like image 655
Mattew Eon Avatar asked Jun 05 '18 17:06

Mattew Eon


1 Answers

I encountered the same problem just now. I had to use cloneDeep (lodash method) to fix the problem.

const translateDeepCopy = cloneDeep(this.translate);

translateDeepCopy.getTranslation(lang).subscribe(res => {
  
});
like image 98
Joven28 Avatar answered Nov 15 '22 04:11

Joven28