Reputation: 951
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.
Upvotes: 4
Views: 8076
Reputation: 416
Create a factory function that loads language data and provide that function to the APP_INITIALIZER
DI token. The function will be executed during the application bootstrap process, and the needed translations will be available on startup.
Here is an example for Transloco:
export function appInitializerFactory(translateService: TranslocoService) {
return (): Promise<Translation> => {
return lastValueFrom(translateService.load('en'))
}
}
@NgModule({
...
providers: [
{
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [TranslocoService],
multi: true
},
...
],
bootstrap: [AppComponent]
})
export class AppModule {}
You can read more about Angular APP_INITIALIZER Injection Token here
Upvotes: 0
Reputation: 951
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 => ...)
Upvotes: 7