Search code examples
angularangular-servicesstatic-variablesinjectable

In Angular2, how do I use a value from an injected service to set a static variable?


I have a service that provides config data.

@Injectable()
export class ConfigData {
     someObj: any;

     constructor(private http: HttpClient) {
          this.http.get('/config-data').subscribe((data) => {this.someObj = data})
     }
}

And now I want to use the object to set a static variable in another service.

@Injectable()
export class AnotherService {
     public static A_STATIC_VAR = ConfigData.someObj.specific_value

     constructor(){}
}

If I add ConfigData to the constructor in AnotherService it's useless because it doesn't assign the value to the static variables in time. They are already "undefined" by the time they are used elsewhere.

Is there any way to accomplish this?


Solution

  • For handling such cases, to initalize configuration setting to be available before application boots up, you could use APP_INITALIZER provider. APP_INITALIZER collect can take promises and it will resolve those promises before application intialize. In your case it will make sure that ConfigData is ready before you're going to use it, when application starts.

    @NgModule({
      imports: [HttpClientModule],
      providers: [
        ConfigData,
        { 
          provide: APP_INITIALIZER, 
          useFactory: (configData: ConfigData) => {
             return () => configData.getConfiguration().toPromise()
          }, 
          deps: [ConfigData], 
          multi: true 
        }
      ]
    })
    export class AppLoadModule { }
    

    Service

    @Injectable()
    export class ConfigData {
         someObj: any;
    
         constructor(private http: HttpClient) {
    
         }
         //created method to return observable, 
         //so that we can use it in APP_INITIALIZER
         getConfiguration(){
            return this.http.get('/config-data').do(
               (data) => {this.someObj = data}
            );
         }
    }