ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.51k stars 575 forks source link

Changing language in a component doesn't propagate to lazy loaded modules #1401

Closed RikudouSage closed 1 year ago

RikudouSage commented 1 year ago

I have this setup:

Any help would be appreciated, I tried adding TranslateService to the providers list but it didn't have any effect, I tried pretty much every answer on StackOverflow I could find and none had any effect.

iKarl commented 1 year ago

Hi, sorry for my English.

I just implemented the library, and the documentation says that if you load a deferred module, in that module you have to redefine the service but with: TranslateModule.forChild()

Now it's not enough for the module to detect the language change, you have to make an observable to detect that change and propagate it, at least that's how I solved it.

Apart from detecting that the: currentLang is not populated I don't know for what strange reason it always sends it to me: undefined until I make a change and pass it to the observer is that the currentLang is populated!

RikudouSage commented 1 year ago

I managed to solve it.

In shared module import it like this (no forRoot or forChild):

  imports: [
    TranslateModule,
  ],
  exports: [
    TranslateModule,
  ]

In app module I configured this:

  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient],
      },
      defaultLanguage: 'en',
      missingTranslationHandler: {
        provide: MissingTranslationHandler,
        useClass: AppMissingTranslationsHandler,
      },
    }),
  ],

That way the TranslateService is the same across modules.