Angular Does APP_INITIALIZER work inside of lazy loaded modules
Asked Answered
T

3

14

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?

Transpacific answered 11/4, 2018 at 20:13 Comment(1)
I don't think so #40523438. Come to think of it, it makes sense since it's called APP_INITIALIZERGenera
E
23

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?

Escort answered 23/8, 2019 at 12:57 Comment(0)
G
3

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)

Genera answered 11/4, 2018 at 21:1 Comment(0)
F
1

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.

Frustration answered 6/10, 2021 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.