2

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.

Conde
  • 785
  • 15
  • 31
  • 2
    I don't know specifically about transloco, but it looks like you are calling a synchronous function "this.translate.translate()", and your TranslocoHttpLoader has an asynchronous set up call in getTranslation. It seems like a race condition. – cjd82187 Jul 07 '20 at 15:10

1 Answers1

5

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

Conde
  • 785
  • 15
  • 31
  • 1
    How do I ensure that the translation files have been successfully loaded by the time I invoke `translate`? – 303 May 17 '22 at 09:11