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 ?
As mentioned earlier, the APP_INITIALIZER is run when the application is initialized. The Angular suspends the app initialization until all the functions provided by the APP_INITIALIZER are run. If any of those intializers return a promise, then the angular waits for it to resolve, before continuing with the App initialization
With this, we can use the Injector service to get a handle to the Angular Router, reset the config, and pass in a filtered set of routes. The Injector is used since you would otherwise get a circular reference by attempting to inject the Router.
The Angular suspends the app initialization until all the functions provided by the APP_INITIALIZER are run. If any of those intializers return a promise, then the angular waits for it to resolve, before continuing with the App initialization
But our initializeApp1 is a function and needs AppInitService to be injected as the argument. We do that by using the deps: flag and let angular know that it needs to create a instance of AppInitService and inject it to the initializeApp1 function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With