Hierarchical Injector in Angular: What It Is and How It Works
hierarchical injector is a system that manages dependencies by creating a tree of injectors, where child injectors can inherit or override services from parent injectors. This allows different parts of an app to have their own instances of services or share common ones, improving modularity and flexibility.How It Works
Think of Angular's hierarchical injector like a family tree for services. At the top, you have a root injector that holds global services shared across the whole app. Then, each component or module can have its own child injector, which can either use the parent's services or provide its own versions.
This setup means if a child injector doesn't find a service, it asks its parent. This continues up the tree until the service is found or an error occurs. It's like asking your parents for something, and if they don't have it, they ask their parents, and so on.
This system helps Angular apps be more organized and efficient by controlling where and how services are created and shared.
Example
This example shows a parent component providing a service, and a child component overriding it with its own instance.
import { Component, Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MessageService { message = 'Hello from root service'; } @Injectable() export class ChildMessageService extends MessageService { message = 'Hello from child service'; } @Component({ selector: 'app-child', template: `{{ messageService.message }}`, providers: [ChildMessageService] }) export class ChildComponent { constructor(public messageService: MessageService) {} } @Component({ selector: 'app-parent', template: `<app-child></app-child> {{ messageService.message }}` }) export class ParentComponent { constructor(public messageService: MessageService) {} }
When to Use
Use the hierarchical injector when you want different parts of your Angular app to have their own versions of a service. For example, if you have a user profile component that needs a special version of a logging service, you can provide it only there without affecting the rest of the app.
This is helpful for modular apps, lazy-loaded modules, or when you want to limit the scope of a service to improve performance or avoid unwanted shared state.
Key Points
- The hierarchical injector creates a tree of injectors for flexible service management.
- Child injectors can override or inherit services from parent injectors.
- This system improves modularity and allows scoped service instances.
- It helps avoid global shared state when not desired.