Angular Hierarchical Dependency Injection

less than 1 minute read

In 0008-7- angular: Hierarchical Dependency Injection video session, you will see how Angular hierarchical dependency injection system works. You will discover how same service can be scoped by component rather than the entire app.

As we know Angular dependency injection system is hierarchical in nature. There is a tree of injectors that parallels an app's component tree. We can reconfigure the injectors at any level of that component tree. If a component requests an instance, dependency Injector looks upwards in the component tree starting from node towards the root and takes the first provider it finds. If an instance for this provider was already created previously, that instance is used, otherwise a new instance is created.

We can configure providers for different injectors in the injector hierarchy. An internal platform-level injector is shared by all running apps. The AppModule injector is the root of an app-wide injector hierarchy, and within an NgModule, directive-level injectors follow the structure of the component hierarchy. The choices you make about where to configure providers lead to differences in the final bundle size, service scope, and service lifetime.