Sub topic 8
The Injector Hierarchy
Earlier chapters treated "the injector" as one container that hands out services. A running Angular application actually has many injectors arranged in two linked trees. Which instance a consumer receives depends on where the consumer sits in those trees and where the provider was registered. This chapter explains that structure and the lookup algorithm, so you can predict the result of any inject() call before running it.
This chapter assumes you already know:
- how to create a service with
@Injectable({ providedIn: 'root' }) - how to inject it with
inject()or a constructor parameter - how to register providers in
bootstrapApplication, and the basic provider recipes - standalone components and the Angular router
Two Kinds of Injector
Angular has two families of injectors, and each has its own job.
| Injector type | Created for | Where its providers come from | Typical lifetime |
|---|---|---|---|
| Environment injector | The application, and each lazy-loaded route that declares providers | `providedIn: 'root'`, `bootstrapApplication` providers, route `providers` | The whole app, or as long as the route's injector exists |
| Element injector | Each component or directive instance that declares providers | The `providers` and `viewProviders` arrays in `@Component` / `@Directive` | As long as the element exists in the view |
The environment injectors form a chain of their own:
- NullInjector sits at the very top. It holds nothing. Its only job is to throw
NullInjectorErrorwhen a lookup reaches it. - Platform injector holds platform-level services that every application on the page shares. You rarely touch it.
- Root environment injector holds everything from
providedIn: 'root'and theprovidersarray ofbootstrapApplication. - Child environment injectors are created for routes that have a
providersarray, and for lazy-loaded route configurations.
Element injectors follow the component tree. Every element that hosts a component or directive can have one. In practice, Angular only does real work for elements whose component or directives declare providers. An element injector's parent is the element injector of its parent in the logical view tree, which is the tree of components as written in templates.
The Resolution Algorithm
When code calls inject(SomeToken), Angular runs a two-phase search.
Phase 1: walk the element injectors. The search starts at the element injector of the requesting component or directive. If that injector has a provider for the token, it returns that instance and stops. Otherwise it moves to the parent element injector, and repeats until it reaches the root of the component tree.
Phase 2: walk the environment injectors. If no element injector matched, Angular switches to the environment injector that belongs to the requesting component. That is the injector of the route that rendered it, or the root injector if no route injector applies. It walks up that chain: route injector, its parent route injectors, root, platform.
Failure. If the search reaches the NullInjector, Angular throws an error like this:
NullInjectorError: R3InjectorError(Standalone[AppComponent])[AdminStore -> AdminStore]:
NullInjectorError: No provider for AdminStore!The bracketed path in that message shows the chain of dependencies Angular was resolving when the lookup failed. Read it left to right to find which service asked for the missing one.
The rule to remember is that the nearest provider wins. A provider registered closer to the consumer shadows one registered further up, so the consumer receives a different instance.
Tracing a Concrete Example
The following code makes instance identity visible. Each CounterService instance gets a sequential id, so you can see which instance each component received.
import { Component, Injectable, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
let nextId = 0;
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly id = ++nextId;
}
@Component({
selector: 'app-leaf',
standalone: true,
template: `<p>{{ label }} sees CounterService #{{ counter.id }}</p>`,
inputs: ['label']
})
export class LeafComponent {
label = '';
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-isolated',
standalone: true,
imports: [LeafComponent],
providers: [CounterService],
template: `
<p>Isolated sees CounterService #{{ counter.id }}</p>
<app-leaf label="Leaf inside isolated" />
`
})
export class IsolatedComponent {
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [LeafComponent, IsolatedComponent],
template: `
<app-leaf label="Leaf A" />
<app-leaf label="Leaf B" />
<app-isolated />
`
})
export class AppComponent {}
bootstrapApplication(AppComponent).catch(err => console.error(err));Assuming the app renders in template order, the output is:
Leaf A sees CounterService #1
Leaf B sees CounterService #1
Isolated sees CounterService #2
Leaf inside isolated sees CounterService #2Here is how each lookup goes:
- Leaf A and Leaf B find no element provider in themselves or in
AppComponent. Phase 2 reaches the root injector, which creates instance #1 on first request and caches it. - IsolatedComponent lists
CounterServicein its ownproviders, so its element injector matches immediately and creates instance #2. - The leaf inside isolated misses on its own element injector, then finds the provider on its parent,
IsolatedComponent. It shares instance #2.
The ids depend on creation order, and Angular creates instances lazily on first request. The numbers matter less than the grouping: the two outer leaves share one instance, and the isolated subtree shares another.
Route Environment Injectors
Routes can declare providers. Angular then creates a child environment injector for that route and its children.
import { Injectable } from '@angular/core';
import { Routes } from '@angular/router';
@Injectable()
export class AdminStore {
readonly createdAt = Date.now();
}
export const routes: Routes = [
{
path: 'admin',
providers: [AdminStore],
loadComponent: () =>
import('./admin/admin.component').then(m => m.AdminComponent)
}
];Every component rendered under /admin can inject AdminStore, and all of them share one instance. Components outside that route get NullInjectorError, because the root injector does not know about AdminStore.
A route environment injector is created the first time the route activates. Angular normally keeps it for the life of the application, even after you navigate away. Coming back to /admin therefore returns the same AdminStore, not a fresh one. If you want per-visit state, provide the service on the routed component instead. Element injectors are destroyed when their component is destroyed.
Gotchas and Failure Modes
Accidental duplicate singletons
If a service is already providedIn: 'root' and you also list it in a route's or component's providers, you create a second instance. Code under that route or component then sees different state from the rest of the app. This is the most common cause of reports like "my cart is empty on this page but full on that one". Search for every place that lists the class in a providers array.
Dependencies resolve from the provider's injector
A service's own dependencies are resolved from the injector that created the service. The consumer's injector does not matter. A root service is created by the root injector, so when it calls inject(X), the lookup starts at root. It never sees element injectors. The following fails even when the requesting component provides FormDraftService:
import { Injectable, inject } from '@angular/core';
import { FormDraftService } from './form-draft.service';
@Injectable({ providedIn: 'root' })
export class AutosaveService {
// Throws NullInjectorError unless FormDraftService is also available
// in an environment injector. Element providers are invisible here.
private readonly draft = inject(FormDraftService);
}To fix it, either provide AutosaveService at the same component level so it is created by that element injector, or pass the draft into a method as an argument.
Logical tree, not DOM tree
Element injector parents follow the component tree as declared in templates. Content projection with <ng-content> does not change this. A projected component's injector parent is the component whose template wrote it, not the component that projects it. The same applies to overlays and portals that move DOM nodes elsewhere on the page. Injection follows where Angular created the view, not where the node ends up in the DOM.
Dynamically created components
When you create a component with ViewContainerRef.createComponent, its element injector parent is the injector at that view container's location, unless you pass an explicit injector option. Dialog libraries often accept an injector option for this reason. Without it, the dialog content cannot see services provided by the component that opened it.
Deciding Where to Provide
| You want | Provide it in |
|---|---|
| One app-wide instance, removed by tree shaking if unused | `@Injectable({ providedIn: 'root' })` |
| App-wide configuration or a third-party provider function | `bootstrapApplication` `providers` |
| One instance shared by a feature area, kept after leaving it | Route `providers` |
| A fresh instance per component, shared with its children | Component `providers` |
Start at root and move a provider closer to its consumers only when you need isolation or per-instance lifetime.
Exercise
AppComponent renders two instances of PanelComponent. PanelComponent lists ThemeService in its providers, and ThemeService is also providedIn: 'root'. A ButtonComponent inside each panel injects ThemeService, and a HeaderComponent directly inside AppComponent injects it too. How many ThemeService instances exist, and which components share each one?
Show answer
Three instances. The root injector creates one for HeaderComponent, because no element injector above it provides ThemeService. Each PanelComponent's element injector creates its own instance, and the ButtonComponent inside each panel shares its panel's instance, because the nearest provider wins.
Exercise
A service marked providedIn: 'root' calls inject(TableStateService). TableStateService is provided only in DataTableComponent's providers array. The root service is first injected by a component inside DataTableComponent. Why does this throw NullInjectorError, and give one fix.
Show answer
The root service is created by the root environment injector, so its dependencies resolve from root upward and never consult element injectors, whoever requested it first. One fix is to move the service from providedIn: 'root' into DataTableComponent's providers, so the element injector creates it and can resolve TableStateService. Another fix is to pass the table state into the service's methods as arguments.
Exercise
A route declares providers: [ReportStore]. A user visits /reports, navigates to /home, then returns to /reports. Do they get the same ReportStore instance? How would you get a fresh instance on each visit?
Show answer
Yes, they get the same instance. Angular creates the route's environment injector on first activation and normally keeps it, so ReportStore persists. To get a fresh instance on each visit, provide ReportStore in the routed component's providers array instead. Its element injector is destroyed and recreated with the component.