ngx-translate .instant returns key instead of value

Viewed 55481

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.

5 Answers

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------------------------------------

@Injectable()
export class TranslationLoaderResolver {

    constructor(private translate: TranslateService){
    }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>{
        return this.translate.get("last.dummy"); //
    }

}

---------------------ROUTING MODULE------------------

let routing = RouterModule.forChild([
    {path: "dashboard", component: DashboardComponent, resolve: {model: TranslationLoaderResolver},
     children: [
        ........//here you can omit Resolver
        },
}

-----Files i18n-----

In last line add the line----> "last.dummy"="dummy translation"

I hope this can help

You can also make a dummy call, and await for the response. After the response, every instant call will work because its sure than the translations are loaded.

async ngOnInit() {
  await this.translate.get('dummyTranslation').toPromise().then();
  this.translate.instant("realTranslation");

Just wrap your $translate.instant with the onReady like so:

$translate.onReady(function () { //Code here })

Just a reminder: Remember to clear the localStorage. It was my mistake.

Related