4

We have a large Angular 4 application using lazy loading along with the preloading strategy of preloadAllModules. We are using Angular CLI.

While looking at a memory issue in the Chrome inspector, I noticed that we have multiple module instances everywhere.

enter image description here

If I am reading this right, we have 83 instances of TranslateModule and HttpModule etc...

Only thing I can think of is that every lazy loaded module has its own root which needs to create its own module for that bundle?

Is it possible to get rid of all these instances or is that just how it works?

Thibs
  • 8,058
  • 13
  • 54
  • 85

2 Answers2

7

Is it possible to get rid of all these instances or is that just how it works?

Yes, just import them into root AppModule. However, while you can avoid putting HttModule into every loaded module and can import it only once into root AppModule, you can't avoid duplication for RouterModule which should be used like this RouterModule.forChild(routes).

The duplication happens because every lazy loaded module has its own injector with its own instances of all imported modules. So if you have 83 lazy-loaded modules and each module imports HttpModule and RouterModule you will have 83 instances of each imported module.

For more information read here:

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • I added my shared modules and components to a SharedModule and even though I import that into my AppModule, I'm still required to import the SharedModule into my lazy loaded module. Without it, the compiler can't find the proper definitions. Does importing this twice duplicate instances of the code? Is my SharedModule cached? – afriedman111 Nov 25 '20 at 19:10
2

You should put all of these shared modules into a core module which is only ever loaded once and only imported by the app module

bryan60
  • 28,215
  • 4
  • 48
  • 65
  • 1
    `RouterModule` should be imported in each lazy loaded module, you can't avoid that – Max Koretskyi Nov 01 '17 at 15:31
  • the routermodule is a different case, each module needs it's own. I meant cases where modules don't need their own, and they can use a shared instance. – bryan60 Nov 01 '17 at 15:32
  • yes, so he can't avoid having 83 instances and that's by design – Max Koretskyi Nov 01 '17 at 15:33
  • 1
    he can avoid 83 instances of the http module and the translate module... quite easily. just because he can't eliminate all duplication doesn't mean he shouldnt eliminate it where he can. – bryan60 Nov 01 '17 at 15:50