1

In my angular code, I added code in main.ts, which call my service to load the config

main.ts

  myConfigService.loadConfig();
  platformBrowserDynamic().bootstrapModule(AppModule).catch(err => 
    console.log(err));

in myService code

import { Injectable } from '@angular/core';
import { Utilities } from './misc/utilities';
import { LogLevel } from 'msal';


export let config: any = {};

@Injectable()
export class MyConfigService {
  public loadAppConfig() {
    config = {clientId: 'asdkjflkjfadslfkj', popUp: true};
  }
}

In my app.module.ts

import { config } from './services/my-config.service';

importS: [
  MsalModule.forRoot({
    clientId: config.clientId
  })
]

When I debug thru the code, the service is setting the export config object. When I get to the app.module.ts, the clientId is undefined.

Thanks.

1
  • Shouldn't it be loadAppConfig() instead of myConfigService.loadConfig(); in main.ts ? Commented Jul 22, 2019 at 19:07

1 Answer 1

2

main.ts is not a module but a simple script-file, executed from top to bottom. It is referenced only by angular-cli.json for handling the startup of the application.

Solution: 1:

The Injectable MyConfigService is only available when the AppModule gets loaded and it's scope/providers etc are defined/available for use by the application. So whatever you see while bootstrapping is not available for your app to use.

You should be using the providers array of AppModule to set up and load any initial configuration.

 providers: [{
            provide: APP_INITIALIZER,
            useFactory: initializeMyApp,
            deps: [MyConfigService ],
            multi: true
        },
    ],


export function initializeMyApp(myConfigService : MyConfigService ) {
  return (): Promise<any> => myConfigService.loadConfig()   
              //Make sure to return a promise!
                             .toPromise().then( config: any) => {
                        // some logic here 
               }
}

Solution 2:

  1. Add a JSON config file to the /src/assets/ folder (so that is copied on build)
  2. Create an MyConfigService to load and distribute the config
  3. Load the configuration using an APP_INITIALISER as shown above in Solution 1.
Sign up to request clarification or add additional context in comments.

2 Comments

HI, Thanks for the guidance. I added the providers section but I got the following error StaticInjectorError(AppModule)[InjectionToken Application Initializer -> MyConfigService
I think this error occurs because you need to import your service or any other dependency used ( like HttpClientModule) in service to the AppModule

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.