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?
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. Maybe you can help it gain developer's attention?
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)
what about routing Guard CanLoad
for lazy loading routes or CanActivate
for regular routes? You can implement your logic inside the guard before the module is loaded but always return from that guard Observable to load this module after module init logic is done.
© 2022 - 2024 — McMap. All rights reserved.