Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular. Router DI not working when using APP_INITIALIZER

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;

enter image description here

Here is plunker

Any thoughts how could it be fixed / worked around ?

like image 975
Alex Kalmikov Avatar asked Mar 27 '17 16:03

Alex Kalmikov


1 Answers

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
};
like image 101
Johan Polson Avatar answered Sep 19 '22 16:09

Johan Polson