ngx-translate: translations are not shown on reload
Asked Answered
C

2

6

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

Crabbed answered 3/11, 2017 at 8:40 Comment(1)
Try the new library Transloco.Monoplane
I
0

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);
}
Inhibition answered 28/8, 2019 at 3:15 Comment(0)
C
-2

Surround the line with minimal timeout it will work then.

setTimeout(()=> {
          variable: string = this.getTranslation("key-in-my-json-file");  
}, 500);
Compliment answered 3/11, 2017 at 10:55 Comment(1)
This way it doesn't work at all, all I get is empty strings.Crabbed

© 2022 - 2024 — McMap. All rights reserved.