2

I have an Angular 5 app which needs to load some config files from a service (from VSTS) before the app actually starts. I do this by loading a JSON file on bootstrap in app.module.ts:

// above the NgModule-decorator
export function init(settingsProvider: SettingsProvider) {
  return () => settingsProvider.loadConfig();
}

// in providers-array of the @NgModule decorator
providers: [{
    'provide': APP_INITIALIZER,
    'useFactory': init,
    'deps': [SettingsProvider],
    'multi': true
}

This loads a JSON config file inside the settingsProvider (which is a standard service loading a JSON file). Now I need some parameters of this settingsProvider within my environment variables.

(let me show you my settingsProvider:)

@Injectable()
export class SettingsProvider {

  private config : any;

  constructor(private http: Http) {
  }

  public loadConfig() : Promise<any>{
    return this.http.get("assets/client-config.json")
      .map(res => res.json())
      .toPromise()
      .then(settings => {
        this.config = settings
      });
  }

  public get configuration(): any {
    return this.config;
  }
}

But since the environment.ts is just a constant, I cannot inject any service there.

So my desired solution would be something like this:

environment.ts

export const environment = {
  production: true,
  apiBaseUrl: '/',
  clientId: settingsProvider.configuration.clientId,  // <-- Here's the problem, because I cannot inject settingsProvider
  enableAdalDebug: false
};

Does anyone know a solution for that problem?

4
  • Hi, there is a good reason why the environment file is constant. But as I understand you correctly, you already inject the SettingsProvider. Is it not possible to inject the SettingsProvider (which holds the clientId) into your services or components, where you need the clientId?
    – alfredson
    Feb 1, 2018 at 10:06
  • No, I haven't injected it yet. I'm using the variable in another service which sends config information to Azure AD for login. Actually I never change a value of the constant, since the settingsProvider information is loaded while bootstrapping. So I just need a way to inject a service in the environment.ts :)
    – dave0688
    Feb 1, 2018 at 10:32
  • I don't think that this is possible, but tell me if you find a solution!
    – alfredson
    Feb 1, 2018 at 10:58
  • Can you provide the detail workflow of your app? Feb 2, 2018 at 3:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.