I'm preloading app configuration from server with APP_INITIALIZER
in following way, AppModule
:
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: configServiceFactory,
deps: [ConfigService],
multi: true
}
],
Then, ApiService
injected manually from ConfigService
:
@Injectable()
export class ConfigService {
private api: ApiService;
public constructor(
private injector: Injector
) {
// Avoid cyclid dependencies, inject manually:
this.api = injector.get(ApiService);
}
And finally router
is undefined when injected in ApiService
import { Http, Headers, RequestOptionsArgs, Response } from '@angular/http';
import { Router } from '@angular/router';
@Injectable()
export class ApiService {
constructor(
private router: Router,
private http: Http
) {
console.log(router, 'router'); // undefined
debugger;
Here is plunker
Any thoughts how could it be fixed / worked around ?
This works works in anguler 4
import { APP_INITIALIZER, Provider, Injector } from '@angular/core';
export function appInitializerFactory(
injector: Injector
): () => Promise<any> {
return () => {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
const router = injector.get(Router);
// do stuff
resolve(this.config);
});
});
}
}
export const appInitializerProvider: Provider = {
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [
Injector
],
multi: true
};