Angular 2: Dynamicly get LOCALE_ID (resolve per request)
Asked Answered
M

0

6

I'm trying to inject LOCALE_ID to my custom components and track it on each ngOnChanges event in case it has been changed (to reinit component with other language).

In AppModule i've got LOCALE_ID provider that returns current language code ('en','fr' and etc):

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

By default OpaqueToken LOCALE_ID registered as 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 LOCALE_ID dependency to get current locale.

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

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

Requirements:

  1. I don't want custom component to know something about my I18NextService

  2. I don't want to change type returned after LOCALE_ID resolved. This can break other libs\controls that expect LOCALE_ID to be string. That is why i can't resolve LOCALE_ID as factory function.

There would no problem if i could just register transient resolver, but angular 2 DI seems doesn't have this feature (Aurelia does)

Suggestions are welcome!

Mohsen answered 24/1, 2017 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.