Angular2 - asynchronous dependency injection

I am using Angular2 v2.2.3

I created a generic module with the forRoot () function, for example:

... public static forRoot(): ModuleWithProviders { return { ngModule: CommonsModule, providers: [ SomeOtherDependency, { provide: ConfigService, useFactory: ConfigFactory, deps: [Http] } ] }; 

Here is my ConfigFactory:

 export function ConfigFactory(http:Http):Promise<ConfigService> { return http.get('confg/config.json').map(r => { return new ConfigService(r); }).toPromise(); } 

I also tried returning Promise and Observable.

SomeOtherDependency defined in providers requires ConfigService. The problem is that Angular does not introduce the value permitted by promise, but by promising itself.

How can I make Angular wait for the promise to be resolved with the correct dependency, and only then add it to the other dependencies?

I have tried different approaches and the value always introduced is promising or observable. Just like iniector ignores return type factory. I need to download some json files before running the whole application

+7
asynchronous dependency-injection angular
source share
1 answer

I found a problem.

I returned a promise from my factory when I needed to return a function. I also skipped the "multi" argument from the vendor section. Here the factory is updated, which works with APP_INITIALIZER:

 export function ConfigFactory(config:ConfigService, http:Http):Function { return () => config.load(http); } 

And in the module:

 providers: [ ConfigService, { provide: APP_INITIALIZER, useFactory: ConfigFactory, deps: [ConfigService, Http], multi: true }, ] 
+3
source share

All Articles