Angular: Set LOCALE_ID from config file

Viewed 43

I wonder if there is a way to set locale of application from config file through LOCALE_ID.

In app.module.ts there is an APP_INITIALIZER which loads config into ConfigService. And I tried to put there also a LOCALE_ID provider with a reference to ConfigService, which the config is already loaded in.

const initConfigProvider = {
  provide: APP_INITIALIZER,
  useFactory: (confService: ConfigService) =>
    () => confService.loadConfig$().toPromise(),
  deps: [ConfigService],
  multi: true
};
const initLocaleProvider = {
  provide: LOCALE_ID,
  useFactory: (confService: ConfigService) =>
    () => { return confService.config.uiCulture; },
  deps: [ConfigService]
};

@NgModule({
  ...
  providers: [
    ...
    initConfigProvider
    initLocaleProvider
  ]
})

Now, there are these errors:

ERROR TypeError: value.replace is not a function
    at CldrIntlService.set localeId [as localeId] (index.js:196:1)
    at new CldrIntlService (index.js:184:1)
    at cldrServiceFactory (index.js:134:1)
ERROR Error: Cannot instantiate cyclic dependency! IntlService
    at throwCyclicDependencyError (core.js:5439:1)
    at R3Injector.hydrate (core.js:11245:1)
    at R3Injector.get (core.js:11071:1)
ERROR Error: InvalidPipeArgument: 'locale.toLowerCase is not a function' for pipe 'DecimalPipe'
    at invalidPipeArgumentError (common.js:4152:1)
    at DecimalPipe.transform (common.js:4887:1)

So, can this example be fixed by any minor change or should I choose completely different way?

2 Answers

useFactory expects synchronous return value. Your function returns promise.

You could take advantage of APP_INITIALIZER to load (asynchronously) & store your config. Then you'd be able to use it synchronously.

Ok, problem resolved.

LOCALE_ID provider needs a function returning a value. APP_INITIALIZER, in opposite, needs a function returning a function, an Observable or a Promise.

The correct solution is:

const initLocaleProvider = {
  provide: LOCALE_ID,
  useFactory: (confService: ConfigService) => { return confService.config.uiCulture; },
  deps: [ConfigService]
};
Related