5

What is the equivalent of the APP_INITIALIZER for feature modules in Angular? I want to run some code when my feature module is (lazily) loaded. That code will want some dependencies injected.

I can't seem to find any similar item for modules though. I've used the Search on the Angular docs website ("initializer") but found nothing. I've gone through parts of the modules documentation and used similar search terms in-browser. But I haven't found anything.

How can you run code (depending on shared services via DI) on module load in Angular?


PS. Possibly this is an XY-problem, where "Y" is my question above. At this point I'm intrinsically interested in learning about "Y", but for completeness, my "X" is that I want my feature module to call back to a MenuService in the shared module to register any menu items that feature module wants to contribute.

1 Answer 1

6

Not sure if it's idiomatic, but I'd answer my question by suggesting to use the module constructor function for this purpose. So for example:

@NgModule({
  imports: [
    CommonModule,
    ThingsRoutingModule,
  ],
  declarations: [
    // Feature module components here
  ],
})
export class ThingsModule {
  constructor(myService: MySharedService) {
    myService.doSomething('From lazy loaded feature module!');
  }
}

Where MySharedService thus gets injected.

Sign up to request clarification or add additional context in comments.

3 Comments

Was trying to use APP_INITIALIZER to do some bootstrapping required for my module but module constructor is better as this can be utilized both for eager & lazy modules
APP_INITIALIZER can wait for async stuff to complete. I fear that this will not work with the constructor solution. If you put an async task in the constructor, everything else of the ThingsModule will still initialize immediately. If you need a async task to be resolved before the module loads, maybe you could use route resolvers: angular.io/api/router/Resolve#description
When I wrote the question in 2018 APP_INITIALIZER could not yet be async. Now that it can i have myself also switched to using that more often as in this example in many cases - though I don't know how it exactly relates to modules and my original question here though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.