الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

Not Every Angular Service Is a Singleton: Hierarchical Injectors Explained

A service is one instance per injector, and every providers array you write creates an injector of its own.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

The cart badge in the header says 0 while the cart page lists three items. Both inject 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

The belief: a service is a singleton by nature. Wherever you provide it, Angular creates it once and hands the same object to everyone who asks.

Most of the time, that's exactly what you see. Nearly every service starts as @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

Angular doesn't have one container. It has a tree of in two layers. Environment injectors hold app-level providers: the root one gets @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

When a component calls 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

An injector creates at most one instance per provider and reuses it. The root injector exists once, so a root-provided service behaves like an app-wide singleton. A component's injector exists once per component instance, so providers: [CartStore] on CartPage means: a new CartStore for every CartPage, visible to it and its descendants, destroyed when that CartPage is destroyed.

Here CartStore is a @Service() with an items signal and an add() method:

TypeScript cart.ts
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}

In the first version, 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

Sometimes it is. The docs' example is a tax-return editor: each open editor needs its own copy of the form state, and a shared instance would let one editor overwrite another's changes. Make that scope explicit:

TypeScript order-editor.ts
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);}

With 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.

Where it's providedHow many instancesWho gets that instance
@Service() or providedIn: 'root'One for the appEveryone who doesn't find a closer provider
bootstrapApplication providersOne for the appSame as root, but always kept in the bundle
A route's providersOne for that route's injectorThe route's components, guards and resolvers
A component's providersOne per component instanceThat component and its descendants
A component's viewProvidersOne per component instanceThe component's own view, not projected content

How to apply it in your project

  1. Audit your providers arraysSearch 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.
  2. Fix NG0201 at the sourceWhen 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.
  3. Mark per-component servicesSwitch services meant to be private to @Service({ autoProvided: false }) and list each one in exactly one place.
  4. Use route providers for feature-wide stateState 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's providers means one per component instance, destroyed with it.
  • Make private scope explicit with @Service({ autoProvided: false }), so a missing provider fails loudly.

📚 المصادر

  1. Hierarchical injectors — Angular
  2. Creating and using services — Angular
  3. Defining dependency providers — Angular
  4. NG0201: No provider found — Angular

التعليقات (0)