Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transloco translate doesn't work the first time

This is my Transloco config:

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  exports: [ TranslocoModule ],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        availableLangs: ['en', 'es'],
        defaultLang: 'en',
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: environment.production,
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader }
  ]
})
export class TranslocoRootModule {}

When I try to translate using the translate method it doesn't work the first time.

constructor(
    private translate: TranslocoService
  ) {
    console.log('<< ', this.translate.translate('dashboard.label'));
  }

If I move through the router to another route and go back the text is translated. It seems that the first time you load the app there is no time to load the translations. Is there a way to fix this? Thanks in advance.

like image 407
Conde Avatar asked Aug 30 '25 17:08

Conde


1 Answers

As the documentation says:

Note that in order to safely use this method, you are responsible for ensuring that the translation files have been successfully loaded by the time it's called. If you aren't sure, you can use the selectTranslate() method instead

This method returns an observable:

translocoService.selectTranslate('hello').subscribe(value => ...)
translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => ...)
translocoService.selectTranslate('hello', {}, 'en').subscribe(value => ...)

Official docs

like image 188
Conde Avatar answered Sep 02 '25 14:09

Conde