I am trying to make a method which would accept string key and return translated string value by using translate.instant(parameter). The problem is that it returns key(parameter). Usually this is returned if it doesn't find translation. I think the problem is that method gets called before loader loads translations.
My app.module.ts imports:
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
createTranslateLoader function:
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
In my app.component:
constructor(public translate: TranslateService){
translate.setDefaultLang('en');
translate.use('en');
}
When I translate in html using pipes it works ok.
You can use TranslateService only when translation file is loaded. If you want to use safely TranslateService.instant you can write an angular resolver. Resolver wait to exec your component code until the observable return a value.
This is the code:
-------------------------RESOLVER------------------------------------
---------------------ROUTING MODULE------------------
-----Files i18n-----
I hope this can help
You are using the
TranslateHttpLoader
which makes an HTTP request when it's asked for translations -translate.use('en')
. If you call theinstant(messageKey)
method before the HTTP call returns, ngx-translate will return the key, since it has no translations yet. So you should use theget(messageKey)
method to get the translation - it's asynchronous and returns anObservable
:You can use the
instant
method only when you are sure that the translations have been already loaded (as in the code example) or you can write your custom synchronous translation loader and useinstant
anywhere.Just wrap your $translate.instant with the onReady like so:
$translate.onReady(function () { //Code here })