Dependency Injection Priority and Hierarchy

Yesterday, we covered the different options to configure our providers with the providedIn syntax. Today, let’s look at how Angular resolves dependency injection using hierarchical injectors.

Let’s assume we have a ButtonComponent that needs a LoginService. Angular is going to check the injector of ButtonComponent to see if a LoginService is available there (since all components have their own injector, configurable with the array of providers or the providedIn syntax).

Suppose the component injector doesn’t know about that service. In that case, it’s going to ask its parent component, then grandparent, making its way up the component hierarchy till it gets to the root injector of the application:

These are called hierarchical injectors: They rely on our component hierarchy. This explains why changing the providers’ config at the component level impacts a component and all its children.

What about modules?

If a service cannot be found in the component tree, then Angular is going to use a similar resolution path using the module hierarchy, from the child modules all the way up to the AppModule.

If no service is found, then Angular throws an error stating no provider is available for that service.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.