Back to results for “Services & Dependency Injection”
Angular › Services & Dependency Injection

What is hierarchical dependency injection in Angular, and how does providing a service at the component level differ from providing it at the root level?

Advanced

Answer

Angular's injector system is hierarchical, meaning a service provided inside a specific component's providers array creates a new, separate instance just for that component and its children, rather than sharing the single application wide instance created when a service is provided at the root level. This lets different parts of an app have their own isolated instance of the same service when needed.
@Component({
  selector: 'app-shopping-cart',
  providers: [CartService] // a new, separate instance just for this component and its children
})
export class ShoppingCartComponent {}
Real-world example A product comparison page needs a completely separate, isolated instance of a comparison service for each individual comparison widget on the page, achieved by providing that service at the component level instead of the root level.

Common follow-ups: How do you decide whether a service should be provided at the root level or a specific component level?;What happens to a component level service instance when that component is destroyed?