
Not Every Angular Service Is a Singleton: Hierarchical Injectors Explained
- كاتب موثّق
- Angular 22
محتويات المقال
CartStore. Months ago, the cart page threw NG0201, Angular's "no provider found" error, and someone fixed it by adding providers: [CartStore] to the page. Later CartStore became a root service so the header could use it too, and nobody removed the old entry. The badge reads the app's cart; the page writes to a cart of its own.
The common misconception
@Service() or @Injectable({ providedIn: 'root' }), and both mean one shared instance for the whole app. Tutorials call services singletons, and the docs describe root-provided services as a single, shared instance. On top of that, providers: [CartStore] reads like registration: in many containers you register a service once and it's available everywhere. In Angular, where you register it decides who shares it.
What actually happens
Injectors form a tree
@Service() classes and the providers you pass to bootstrapApplication, and the router creates child ones for routes that declare providers. Element injectors belong to components and directives: each one that declares providers gets its own injector, so this layer mirrors your component tree.
Lookup walks up and stops at the first match
inject(CartStore), Angular first walks up the element injectors: the component's own, then its parent's, and so on toward the root component. Only if none of them provides CartStore does it move on to the environment injectors, the route's and then root's. The first provider it finds wins, and the injector that holds it owns the instance.
Singleton means one per injector
providers: [CartStore] on CartPage means: a new CartStore for every CartPage, visible to it and its descendants, destroyed when that CartPage is destroyed.
CartStore is a @Service() with an items signal and an add() method:
import { Component, inject } from '@angular/core';// CartStore is declared with @Service(): one instance in the root injector@Component({ selector: 'app-cart-badge', template: `{{ cart.items().length }}`,})export class CartBadge { readonly cart = inject(CartStore); // resolved by root}@Component({ selector: 'app-cart-page', providers: [CartStore], // a second, private CartStore template: `<button (click)="cart.add('Mug')">Add mug</button>`,})export class CartPage { readonly cart = inject(CartStore); // resolved by CartPage's own injector}import { Component, inject } from '@angular/core';// CartStore is declared with @Service(): one instance in the root injector@Component({ selector: 'app-cart-badge', template: `{{ cart.items().length }}`,})export class CartBadge { readonly cart = inject(CartStore); // resolved by root}@Component({ selector: 'app-cart-page', template: `<button (click)="cart.add('Mug')">Add mug</button>`,})export class CartPage { readonly cart = inject(CartStore); // also root: the same instance}CartBadge lives in the header, outside CartPage, so its lookup finds no element provider and ends at root. CartPage finds its own provider first and never reaches root. Two lookups, two instances, two carts. Deleting one line fixes it, because both lookups now end at the same injector.
When a private instance is what you want
import { Component, Service, inject, signal } from '@angular/core';@Service({ autoProvided: false }) // exists only where it's listedexport class OrderDraft { readonly lines = signal<string[]>([]);}@Component({ selector: 'app-order-editor', providers: [OrderDraft], // one draft per editor, destroyed with it template: `<p>{{ draft.lines().length }} lines</p>`,})export class OrderEditor { readonly draft = inject(OrderDraft);}autoProvided: false, the service isn't registered anywhere until a providers array lists it, so forgetting the line in OrderEditor throws NG0201 instead of quietly falling back to a shared instance. Routes follow the same rule one level up: a service in a route's providers is shared by that route's components, guards and resolvers, and by nothing outside it. Older apps hit the same effect with lazy-loaded NgModules, which get a child injector, so a service listed in their providers becomes a second instance next to root's.
@Service() or providedIn: 'root' | ||
bootstrapApplication providers | ||
providers | ||
providers | ||
viewProviders |
How to apply it in your project
Audit your providers arrays Search for providers:in components and routes. For every entry whose class is also root-provided, decide whether a private instance is really what you want.Fix NG0201 at the source When a service has no provider, give it one where it belongs, usually @Service()on the class, instead of adding it to the providers of whichever component threw.Mark per-component services Switch services meant to be private to @Service({ autoProvided: false })and list each one in exactly one place.Use route providers for feature-wide state State shared by one feature's pages, like a checkout flow, belongs in that route's providers: not in root, and not copied into each page.
Key takeaways
A service is a singleton per injector, not per app. inject()walks up element injectors, then environment injectors, and the first provider it finds wins.@Service()means one shared instance; a component'sprovidersmeans one per component instance, destroyed with it.Make private scope explicit with @Service({ autoProvided: false }), so a missing provider fails loudly.
التعليقات (0)