title: Angular 6 - Initialize service with async calls before dependency injection
body: <p>I have a service which based on the environment file, loads up a configuration object in memory. However, the reading of the settings is asynchronous and the application starts before even all the settings are loaded and crashes. Is there any way to 'await' for these functions before the dependency injection is complete.</p>
  
  <p>My service :</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { IAppConfig } from '../models/app-config.model';
  
  @Injectable()
  export class AppConfig {
      settings: IAppConfig;
      version: any;
  
  constructor() {
      this.loadConfig();
  }
  
  // reads env.json file
  // based on which environment it is loads config setting from
  // environment specific config settings.
  
  public loadConfig() {
      return new Promise((resolve, reject) =&gt; {
          const envFile = '/env.json';
          this.readJsonFile(envFile).
              then((envData) =&gt; {
                  const configFile = `assets/appconfigs/config.${envData.env}.json`;
                  this.version = envData.version;
                  this.readJsonFile(configFile).
                      then((configsettings) =&gt; {
                          this.settings = configsettings;
                          resolve(this.settings);
                      });
              });
      });
  }
  
  // reads json file and returns the json object promise
  public readJsonFile(jsonUrl: string): any {
      return new Promise((resolve, reject) =&gt; {
          let retObject: any;
          const xhr = new XMLHttpRequest();
          xhr.overrideMimeType('application/json');
          xhr.open('GET', jsonUrl, true);
          xhr.onreadystatechange = () =&gt; {
              if (xhr.readyState === 4) {
                  if (xhr.status === 200) {
                      retObject = JSON.parse(xhr.responseText);
                      resolve(retObject);
                  } else {
                      reject(`Could not load file '${jsonUrl}': ${xhr.status}`);
                  }
              }
          };
          xhr.send(null);
      });
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I want the settings object to be loaded before the application fires up. The other way was to make this class static and call loadConfig but it is a nightmare for testbeds. Is there anything I could specify when providing the service in the module?</p>