Angular 4 Injecting route in the APP_INITIALIZER

2020-06-16 05:04发布

问题:

I am trying to retrieve a data present in the url in my APP_INITIALIZER

app.module.ts

export function init(config: ConfigService, router: Router) {
    return () => config.load(router);
}


providers : [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: init,
      deps: [ConfigService, Router],
      multi: true
    },
    ConfigService 
    ... 
]

config-service.ts

@Injectable()
export class ConfigService 
    load(router: Router): Promise<any> {
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

Unfortunately I am getting

Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppBrowserModule in ./AppBrowserModule@-1:-1

I also tried using the Injector in the constructor but it didn't work either.

Is what I am trying to do even feasible ?

回答1:

config-service.ts can be rewritten as below.

@Injectable()
export class ConfigService
    constructor(private injector: Injector){}

    load(): Promise<any> {
        const router = this.injector.get(Router);
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

No need to inject Router as a dependency in app.module.ts.



回答2:

What I was trying to do isn't feasible since the APP_INITIALIZER happens before the router init. https://medium.com/hackernoon/hook-into-angular-initialization-process-add41a6b7e



标签: angular