Angular. Router DI not working when using APP_INITIALIZER
Asked Answered
L

1

5

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 ?

Logic answered 27/3, 2017 at 16:4 Comment(0)
W
7

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
};
Wabble answered 18/4, 2017 at 19:55 Comment(2)
While I get the Router this way, the initialization seems to fall in an endless loop with the setTimeout...Hawkinson
I saw that it did not work in your plunger, But I could make it work through. src/app.ts: 31 -> RouterModule.forRoot(), to RouterModule.forRoot([]),Wabble

© 2022 - 2024 — McMap. All rights reserved.