5
votes

In my webapp, I use ngx-translate module for localization. It works ok for html strings which I translate using pipes. I am having problems with strings translated in my ts components. Strings get translate but if I reload page they are empty strings, if I go to other page inside my app and come back they are again normal. I have method defined:

public getTranslation(key: string){
    let str="";
    this.translate.get(key).subscribe(value => {str = value});
    return str;
}

So when I define variables I use:

variable: string = this.getTranslation("key-in-my-json-file")

my configuration in app.module, loader:

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

and in imports:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: (createTranslateLoader),
    deps: [HttpClient]
  }
})

my versions in package.json:

"@ngx-translate/core": "^8.0.0",
"@ngx-translate/http-loader": "^1.0.2",
"typescript": "2.5.2"

and angular version 4.3.6

2
Try the new library Transloco.Bazinga

2 Answers

0
votes

Try using localStorage. For example, I use it in a function when changing the language:

public changeLanguage(lang) {
  this.languageActive = lang;
  this.translateService.use(lang);
  localStorage.setItem("language", this.languageActive);
}
-2
votes

Surround the line with minimal timeout it will work then.

setTimeout(()=> {
          variable: string = this.getTranslation("key-in-my-json-file");  
}, 500);