If you didn’t dive deep into angular dependency injection mechanism, your mental model should be that in angular application we have some root injector with all merged providers, every component has its own injector and lazy loaded module introduces new injector.

But maybe there is some more you should be aware of?

Also a while ago, so-called Tree-Shakeable Tokens feature was merged into master branch. If you are like me, you probably want to know what has changed.

So it’s time to examine all these things and maybe find something new…

The Injector Tree#

Most of angular developers know that angular creates root injector with singleton providers. But seems there is another injector which is higher that injector.

As a developer I want to understand how angular builds injector tree. Here is how I see the top part of Angular injector tree:

Top part of Angular Injector Tree

This is not the entire tree. For now, there aren’t any components here. We’ll continue drawing later. But now let’s start with AppModule Injector since it’s most used part of angular.

Root AppModule Injector#

Well known angular application root injector is presented as AppModule Injectorin the picture above. As it has already been said, this injector collects all providers from transitive modules. It means that:

If we have a module with some providers and import this module directly in AppModule or in any other module, which has already been imported in AppModule, then those providers become application-wide providers.

According to this rule, MyService2 from EagerModule2 will be included into the root injector.

ComponentFactoryResolver is also added to the root module injector by Angular. This resolver is responsible for dynamic creation components since it stores factories of entryComponents.

It is also worth noting that among all other providers we can see Module Tokenswhich are actually types of all merged NgModules. We will come back to this later when will be exploring tree-shakeable tokens.

In order to initialize NgModule injector Angular uses AppModule factory, which is located in so-called module.ngfactory.js file.

AppModule factory

We can see that the factory returns the module definition with all merged providers. It should be well known by many developers.

Tip: If you have angular application in dev mode and want to see all providers from root AppModule injector then just open devtools console and write:

ng.probe(getAllAngularRootElements()[0]).injector.view.root.ngModule._providers
<>

There are also a lot of well known facts which I won’t describe here because they are well covered in angular documentation:

#angular #javascript #dependency-injection

What you always wanted to know about Angular Dependency Injection tree
1.60 GEEK