chenk chenk - 9 months ago 64
AngularJS Question

Detect locale and set it on angular 2 root module using provider

I have a function to detect current locale and I need to set the locale at angular 2 rooot App module via provider. so that i can use that in all other components.

I know i can able to do this like below.


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


But i want to do something like this below if possible.


{ provide: 'Locale', useValue: this.detectLocale() }


Otherwise Please suggest any suitable way to achieve this. Thanks.

Answer Source

Having an AppConfig provider that will store configuration and other constant values may be useful in your app.

import { Injectable } from "@angular/core"

@Injectable()
export class AppConfig()
{
   public endPointUrl: string; // sample configuration value
   public local: string;

   constructor(){
       this.endpointUrl = "";
       this.local = ""; // use detect local logic here
   }
}

and provide a singleton instanse of your configuration class:

{provide: AppConfig, useValue: new AppConfig()}

In this way you can put all your settings and configurations in one place.

Also as I now you can't use strings as provider token. Provider tokens only can be class types.