Angular 2: dynamically get LOCALE_ID (allow for each request)

I am trying to insert a LOCALE_ID into my custom components and track it in every ngOnChanges event if it has been changed (to reuse the component with a different language).

In AppModule, I have a LOCALE_ID provider that returns the current language code ('en', 'fr', etc.):

{
 provide: LOCALE_ID,
 deps: [I18NextService],
 useFactory: (i18next: I18NextService) => {
  return i18next.language; //string: 'en', 'ru'...
 }
}

By default, the OpaqueToken LOCALE_ID is registered as the value "en-US".

{
  provide: LOCALE_ID,
  useValue: 'en-US'
}

Then I implement my component with contructor injector

constructor(private injector: Injector) {
}

And then I resolve the LOCALE_ID dependency to get the current locale.

ngOnChanges(changes: SimpleChanges) {
  let localeId = this.injector.get(LOCALE_ID);
   ...
}

The problem is that the LOCALE_ID provider is registered as singleton and I always get the first resolved value ...

Requirements:

  • I do not want the user component to know something about my I18NextService

  • , LOCALE_ID. libs \, , LOCALE_ID . LOCALE_ID factory.

, , angular 2 DI, , (Aurelia )

!

+4

Source: https://habr.com/ru/post/1667606/


All Articles