In this tutorial, you will learn about Angular Dependency Injection Hierarchy.
The DI hierarchy is a mechanism that determines which instance of a service is injected and where it comes from.
Example:
Suppose I created a User Service and injected it into the constructor of the User Component.
constructor(private userService: UserService) {}
Angular Dependency Injection Hierarchy Levels
Angular Dependency works at multiple levels
1. DI works in Platform Injector.
2. DI works in Root Injector.
3. DI works in Module Injector.
4. DI works in Component Injector.
5. DI works in Element Injector.
1. Platform Injector
We really used this injector because it was created when Angular started.
2. Root Injector
This is the most commonly used injector when you create a service.
Service is a Singleton across the app.
@Injectable({
providedIn: 'root'
})
export class AuthService {}
3. Module Injector
When you use a standalone component, then there is no need for this injector.
@NgModule({
providers: [UserService]
})
export class UserModule {}
4. Component Injector
In the Component injector, the Angular Service is injected into the Component.
Note: When we use this injector, then new instance will be created based on per component.
@Component({
selector: 'app-user',
providers: [UserService]
})
export class UserComponent {}
5. Element Injector
It’s mainly used in Element Injector.
@Directive({
selector: '[highlight]',
providers: [HighlightService]
})
export class HighlightDirective {}
Angular DI Hierarchy Interview Questions
Q 1: Which injector has the highest priority?
Ans: Component injector.
Q 2: Is providedIn: ‘root’ a singleton?
Ans: yes
Q 3: What is hierarchical dependency injection?
Ans: Angular resolves dependencies from child to parent injectors.