Angular Does APP_INITIALIZER work inside of lazy loaded modules

早过忘川 提交于 2020-01-15 10:22:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!