Search code examples
angulartransloco

Angular Transloco usage in ngOnInit()


I know that the following code doesn't work, because the translation file en.json hasn't been loaded, when ngOnInit() is called:

component.ts

ngOnInit() {
  console.log(this.translocoService.translate('hello', { value: 'world' }););
}

en.json

{
  "hello": "Hello",
}

An alternative would be subscribing to:

ngOnInit() {
  this.translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => console.log(value));
}

But in my component I have 30 keys that need to be translated. Should I really subscribe to all of the 30 keys?

Demo: https://stackblitz.com/edit/ngneat-transloco-8xqjqm?file=src%2Fapp%2Fapp.component.ts


Solution

  • Now I found an even better solution: https://ngneat.github.io/transloco/docs/recipes/prefetch/#prefetch-the-user-language

    I now use the APP_INITIALIZER to preload the translation file, before the app initializes. That way the translations are always available, also in the constructor of components.

    This approach is unfortunately nested in the Transloco docs to be easiliy overlooked.