Angular. Router DI not working when using APP_INITIALIZER

二次信任 提交于 2019-12-09 18:20:46

问题


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 ?


回答1:


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
};


来源:https://stackoverflow.com/questions/43051287/angular-router-di-not-working-when-using-app-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!