Transloco translateService.translate does not work in app.component.ts

1.9k Views Asked by At

If I enter the below in my app.component.ts constructor, it does not work.

alert(this.translateService.translate('navigation.dashboard'));

However if I enter this same code in a submodule, it works fine.

This is my .json file:

    "navigation": {
    "dashboard": "Dashboard"
   }

In my app.module.ts, the TranslocoRootModule is imported too.

import { TranslocoRootModule } from './transloco/transloco-root.module';

imports: [
 ...  
 HttpClientModule,
 TranslocoRootModule
],

Did I miss out anything?

1

There are 1 best solutions below

4
On

I ran into this problem as well. What I realized was that the transloco file (i.e. the json file) had not yet loaded when I was trying to get the translation. It seems like the order in which the HTTP requests are being made does not allows all translations json file to load before the component does.

This means, that if you are on a different page, and then navigate to this page through angular, it will/would work (because the translations file has been loaded). This only seemed to be the problem for a refresh on a current page.

In order to get around this, here's what I did:

...
constructor(private translocoService: TranslocoService,
  private translocoHttpLoader: TranslocoHttpLoader ...) {
...
}

ngOnInit(): void {
...
this.translocoHttpLoader.getTranslation(this.translocoService.getActiveLang())).subscribe(translation => {
  alert(translation.navigation.dashboard);
})
...
}

Hope this example helps.