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?
Lazy loading is a useful technique for faster initial page loads. With lazy loading, your application loads faster by shipping only the essential startup code to the browser. Another code is placed inside of feature modules, which are loaded on demand. Lazy loading is a useful technique for faster initial page loads.
Disadvantages of Lazy loading Firstly, the extra lines of code, to be added to the existing ones, to implement lazy load makes the code a bit complicated. Secondly, lazy loading may affect the website's ranking on search engines sometimes, due to improper indexing of the unloaded content.
The APP_INITIALIZER is an instance of InjectionToken . It is a built in Injection token provided by Angular. The Angular will execute the function provided by this token when the application loads. If the function returns the promise, then the angular will wait until the promise is resolved.
Lazy loading helps to keep the bundle size small, which helps reduce load times. We must use the class decorator to create an Angular module @NgModule, and the decorator uses a metadata object that defines the module. The main properties are: import: Components of this module are used with Array with other modules.
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:
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)
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