Sub topic 11
How Angular resolves a dependency
This chapter assumes you know TypeScript classes, standalone components, basic services, and route configuration. It also assumes you have seen inject() and providers. Here you will learn the exact order in which Angular searches for a provider. That order decides whether a component receives a shared instance, a private one, or an error.
The two hierarchies, searched in a fixed order
Angular keeps two injector hierarchies:
- Element injectors follow the DOM tree of components and directives. Each element that declares providers has one.
- Environment injectors hold application-level providers. From the bottom up they are: route injectors, the root injector, and the platform injector.
When code asks for a token, Angular searches the element hierarchy first. If that search finds nothing, Angular searches the environment hierarchy. It never goes back. The order is:
- The element injector of the requesting node (the component or directive, and the other directives on the same element).
- The element injector of each parent element, up to the root component's host element.
- The environment injector the component belongs to. For a routed component this is the route's environment injector, or the root injector if no route creates one.
- Each parent environment injector, up to the root injector.
- The platform injector.
- The null injector, which throws
NullInjectorError. Withoptional: true, you getnullinstead.
The first match wins. A provider that sits near the requester in the component tree therefore hides a provider that is "closer" in the environment hierarchy. A component's providers entry beats a route's providers entry, and the route's entry beats providedIn: 'root'.
Instances are cached per injector
Each injector creates a provider's instance the first time something asks for it, then keeps it. Two consequences follow:
- Every consumer that resolves to the same injector gets the same instance.
- Two injectors that both register the token each build their own instance.
A component-level provider creates one instance for each component instance. When that component is destroyed, its element injector and its services go with it. Angular calls ngOnDestroy on the service if it defines one.
A worked example
This example shows the same token resolving to three different instances.
import { Component, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class IdService {
readonly id = Math.random().toString(36).slice(2, 6);
}
@Component({
selector: 'app-leaf',
standalone: true,
template: `leaf sees {{ ids.id }}`,
})
export class LeafComponent {
protected readonly ids = inject(IdService);
}
@Component({
selector: 'app-branch',
standalone: true,
imports: [LeafComponent],
providers: [IdService],
template: `branch has {{ ids.id }} <app-leaf />`,
})
export class BranchComponent {
protected readonly ids = inject(IdService);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [BranchComponent, LeafComponent],
template: `
root has {{ ids.id }}
<app-leaf />
<app-branch />
<app-branch />
`,
})
export class AppComponent {
protected readonly ids = inject(IdService);
}Walk through each lookup:
| Requester | Element injectors checked | Result |
|---|---|---|
| `AppComponent` | Its own element injector has no `IdService`. It is the root element. | Root environment injector, instance A |
| `LeafComponent` under `AppComponent` | Leaf, then app host. Neither provides it. | Root environment injector, instance A |
| First `BranchComponent` | Its own `providers` lists `IdService`. | New instance B |
| `LeafComponent` inside the first branch | Leaf has none, the parent branch does. | Instance B |
| Second `BranchComponent` | Its own `providers` | New instance C |
| `LeafComponent` inside the second branch | The parent branch | Instance C |
LeafComponent contains no scoping logic. The same class receives different instances depending on where it appears in the tree.
The service's own injector decides what it can see
This rule catches many people. A service gets its dependencies from the injector that creates it, not from the component that uses it.
import { Component, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
readonly name = 'light';
}
@Injectable({ providedIn: 'root' })
export class ReportService {
readonly theme = inject(ThemeService);
}
@Component({
selector: 'app-report',
standalone: true,
providers: [{ provide: ThemeService, useValue: { name: 'dark' } }],
template: `{{ theme.name }} / {{ report.theme.name }}`,
})
export class ReportComponent {
protected readonly theme = inject(ThemeService);
protected readonly report = inject(ReportService);
}The template renders dark / light. ReportService is created by the root environment injector. That injector searches only environment injectors, so it cannot see the component's provider.
To make the service use the component's ThemeService, also list ReportService in the component's providers. Then the element injector creates it, and the lookup for ThemeService starts in the element hierarchy.
Changing the search with modifiers
The options passed to inject() change where the search starts, where it stops, and what happens on a miss:
| Option | Effect on the search |
|---|---|
| `self: true` | Check only the requesting node's own injector. |
| `skipSelf: true` | Start at the parent injector and skip the requester's own. |
| `host: true` | Stop climbing at the host element of the current component. Environment injectors are not searched, with one exception below. |
| `optional: true` | Return `null` on a miss instead of throwing. |
The options combine. A component that provides its own ThemeService and also wants its parent's would write:
import { Component, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-nested-panel',
standalone: true,
providers: [ThemeService],
template: ``,
})
export class NestedPanelComponent {
protected readonly own = inject(ThemeService, { self: true });
protected readonly parent = inject(ThemeService, { skipSelf: true, optional: true });
}Without optional: true, the skipSelf lookup would throw whenever no ancestor provides ThemeService. A token declared with providedIn: 'root' is the exception. The lookup finds it in the root injector, so parent is never null for such a token.
The host option is best learned from viewProviders. A provider in viewProviders is visible to the component's own template, but not to content projected into it. A projected child cannot find it by walking up from its position in the parent's template. This restriction is what host and viewProviders are built around. Treat both as tools for authors of reusable components.
Debugging a wrong or missing instance
Work through the algorithm by hand. Ask these questions in order:
- Who is the requester: a component, a directive, or a service created by an environment injector?
- If it is a service created by an environment injector, which environment injector created it? Skip the element questions.
- Otherwise, list every ancestor element from the requester up to the root. Does any of them declare the token in
providers, or inviewProviderswhen you are inside its own view? - If none does, which route environment injectors sit above the component? Does one declare the token?
- Is the token
providedIn: 'root', or provided inbootstrapApplication?
Typical symptoms and causes:
| Symptom | Likely cause |
|---|---|
| `NullInjectorError: No provider for X` | No injector on the path has the token. The service lacks `providedIn`, or it is provided only on a component that is not an ancestor. |
| Two components that should share state each have their own copy | One or both list the service in `providers`, so each creates its own instance. |
| A service ignores an override on a component | The service is created by an environment injector, so it cannot see element providers. |
| A route's service is shared across the whole app | The same class also has `providedIn: 'root'`, or another route lists it too. Check where each lookup lands. |
Exercise
A route lists CartService in its providers. CartService is also providedIn: 'root'. A component under that route lists CartService in its own providers. A child of that component injects CartService. Which injector supplies it, and which would supply it if the component's providers entry were removed?
Show answer
With the entry, the child gets the instance from its parent component's element injector, because element injectors are searched before any environment injector. Without it, the element search finds nothing, so Angular checks the route's environment injector and finds the route's CartService. The root registration is never reached.
Exercise
A providedIn: 'root' service AuditService injects UserContext. A component provides its own UserContext in providers and injects AuditService. Does AuditService receive the component's UserContext?
Show answer
No. The root environment injector creates AuditService and searches only environment injectors for UserContext. To use the component's UserContext, add AuditService to the component's providers as well, so the element injector creates it.