5

When I recently read the Angular2's doc, it says like this:

What if I import the same module twice?

That's not a problem. When three modules all import Module 'A', Angular evaluates Module 'A' once, the first time it encounters it, and doesn't do so > again.

That's true at whatever level A appears in a hierarchy of imported modules. > When Module 'B' imports Module 'A', Module 'C' imports 'B', and Module 'D' imports [C, B, A], then 'D' triggers the evaluation of 'C', which triggers the evaluation of 'B', which evaluates 'A'. When Angular gets to the 'B' and 'A' in 'D', they're already cached and ready to go.

Angular doesn't like modules with circular references, so don't let Module 'A'......

But I assume the above is stated in the context of all Eager Loading Modules. I doubt if this holds true in a Lazy-load module, for example, If AppModule and a lazy-load feature module both imports a same module(e.g. ModuleA), would ModuleA be loaded twice?

What I think is: two module instance of ModuleA type would be created when AppModule and the lazy-load module loading. Is my understanding correct? Could someone help me clarify it? Thank you in advance.

Community
  • 1
  • 1
IcyBrk
  • 872
  • 8
  • 18

2 Answers2

4

It's unclear what you mean with "loaded".

Angular doesn't load it twice from the server. In subsequent uses it uses it from the cache.

If you mean whether multiple instances are created in memory, then yes.

Lazy loaded modules create a new child scope for dependency injection. If a module is lazy loaded by another module that itself was lazy loaded, the hierarchy of the DI scopes would not make sense.

    RootScope (AppModule)
       /    \
    LazyA  LazyB
     /        \
  LazyC      LazyC

If there were only one instance of LazyC this would require providers of LazyA and LazyB to be available to LazyC. What if LazyB will never be loaded? Then adding the providers wouldn't make sense.

Angular also can't update providers after a scope was created. This is the reason lazy loaded modules introduce a new child scope. Their providers are not added to RootScope as it is the case with all non-lazy loaded modules. Therefore creating a new instance is the only way.

In my opinion this doesn't cause harm though. Except for the DI scope, I don't see how this would make a difference.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
1

According the experiment I did, when I import the same module in a Lazy-Load Module, when that lazy-load is loaded, I can see the constructor of that shared module is get called again. So that answers my question, the answer is Yes. If anyone have different opinion, kindly points out.

IcyBrk
  • 872
  • 8
  • 18