问题
I have a lazy loaded module that I'm trying to add APP_INITIALIZER but its not firing. I have the exact same syntax as my main app where its working as expected. Does a lazy loaded module fire the APP_INITIALIZER?
回答1:
No
From the docs https://angular.io/api/core/APP_INITIALIZER
A function that will be executed when an application is initialized
The app is only initialized once, starting with the main module (the one that is bootstrapped)
回答2:
Unfortunately APP_INITIALIZER is not called in a lazy loaded module, because the application has already been initialized before.
What you can do now:
You may simply utilize the module's constructor, which is called as soon as the module gets initialized, and gets full treatment by the injector:
@NgModule({
...
})
export class MyModule {
constructor( <INJECTIONS> ) {
console.log('Module initialized');
}
}
There are two limitations to this approach:
- You can only use synchronous calls inside
- When the constructor is called, the module is not yet initialized, so, for example, you can't dynamically add routes to the components defined here (which is, sadly, what I wanted to do)
What may help in the future:
There is an ongoing discussion on GitHub about introducing a MODULE_INITIALIZER that gets called after module initialization, which would solve these limitations.
来源:https://stackoverflow.com/questions/49783765/angular-does-app-initializer-work-inside-of-lazy-loaded-modules