Angular 5 and ngx-translate with shared module loose translations if refresh
Asked Answered
V

1

6

I have an angular app that uses ngx-translate. Below the versions:

"@angular/core": "5.2.6",
"@ngx-translate/core": "9.1.1",
"@ngx-translate/http-loader": "2.0.1"

In the AppModule class i added the import below:

imports: [
    .....
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    })
    ......
]
.....
export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

And i created a SharedModule that exports the TranslateModule:

exports: [
    // Modules
    TranslateModule,
    ....
]

Everything works like a charm, except when i refresh a page that is placed in a different module than app module (that imports the SharedModule). In this case I need to navigate back to the home page (coded in the AppModule), once i reach the home page ngx-translate come back to work and i can re-navigate to the other pages with ngx-translate that works.

Can anybody help me? Thanks in advance

UPDATE Seems that the problem is related to the fact that translateService.currentLang is undefined when i refresh the page. If i set programmatically the language in ngOnInit via translateService.use(language) it works. How can i avoid to set manually in every component this check on currentLang variable by setting a default currentLang?

Venu answered 27/7, 2018 at 14:9 Comment(0)
T
7

I had translateModule also in my shared module, and every module was importing this. I exported the TranslateModule within the sharedmodule. Doing this, everything was working as intended and every module had it's translations showing up. Maybe try the same thing and see if it works for you.

TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }

Set useDefaultLanguage via translateService in your bootstrapped component via app.module. That way it's the only place it sets the default language at top level.

Teammate answered 27/7, 2018 at 14:15 Comment(5)
I tried with no luck. if i refresh the page i loose the translation and i still see the keywords instead of the valuesVenu
do your other modules import the shared modules? and you put the translatemodule loader + the function to the path in the shared module?Teammate
i shared an update in the main question. Do you have any idea on that?Venu
set ngOnInit via translateService.use(language) in the component you bootstrap in your app.module -- should be the only place.Teammate
you are right! Thanks Taranjit Kang, i am going to assign you the right answer :)Venu

© 2022 - 2024 — McMap. All rights reserved.