Sub topic 10
Inspecting dependency injection
This chapter assumes you have read the earlier chapters on the component explorer and on inspecting properties. It also assumes you know how Angular dependency injection (DI) works at a basic level. That means @Injectable, providedIn: 'root', the providers array on a component, and the inject() function. You need a development-mode app with Angular DevTools installed.
DI bugs often show up as odd behavior, not as errors. Two components that should share a service each get their own copy. A value you set in one place is missing in another. A provider you overrode is ignored. These bugs come from where a provider is registered, and the source code alone doesn't always show you that. DevTools shows the injector hierarchy of the running app, so you can see which injector supplies each dependency.
The two injector trees
Angular resolves a dependency by walking a chain of injectors. There are two kinds.
- Element injectors exist on elements in the template. A component or directive that declares
providersorviewProviderscreates one. They form a tree that matches the DOM structure. - Environment injectors hold providers that belong to the application or to a route. They include the root injector (where
providedIn: 'root'services live), injectors created for lazy-loaded routes, and the platform injector at the top.
When a class asks for a token, Angular checks the element injector of the requesting node first. It then walks up through the parent element injectors. When it runs out of elements, it moves to the environment injectors, and finally to the platform injector. If no injector has a provider, you get a NullInjectorError. If the dependency was marked optional, you get null.
The Injector Tree tab draws these same two trees for your running app. That makes it a direct check of the resolution order above.
Opening the Injector Tree
- Open the browser developer tools and choose the Angular panel.
- Switch from the Components tab to the Injector Tree tab.
- Wait for the tree to render. DevTools reads the live injector structure, so a large app can take a moment.
If the tab is missing, check the version of the extension and the version of Angular your app uses. Injector inspection depends on debugging hooks in the framework, so older Angular versions may not support it. The panel also only works for apps running in development mode, as with the rest of DevTools.
The tab shows a tree diagram of injectors. Nodes for environment injectors and nodes for element injectors are drawn in the same view, so you can see where one hierarchy hands over to the other. Selecting a node highlights the path from that injector up to the root. This path is the lookup route Angular follows when a dependency isn't found locally.
Reading the providers of an injector
Select a node and the side panel lists the providers registered in that injector. The list tells you:
- Which tokens the injector can resolve itself.
- Whether the injector is an element injector (a component or directive) or an environment injector (root, a route, or the platform).
- For element injectors, which tokens come from
providersand which fromviewProviders.
Use this list to answer the question "does this injector own a provider for token X?" If the token appears on an element injector near your component, that provider shadows anything registered higher up. If it appears only on the root injector, every consumer shares one instance.
A token that doesn't appear at all may still be resolvable. Services marked providedIn: 'root' are tree-shakable. Angular registers them in the root injector the first time something requests them. A root service nobody has used yet may therefore be missing from the list. Treat absence from the list as a hint, not proof.
Worked example: two copies of a service
The following app has a shopping cart that must be shared. A well-meaning developer added the service to a component's providers array.
import { Component, Injectable, inject, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
readonly items = signal<string[]>([]);
add(item: string): void {
this.items.update((list) => [...list, item]);
}
}
@Component({
selector: 'app-product-list',
standalone: true,
// Bug: this creates a new CartService for every ProductListComponent.
providers: [CartService],
template: `<button (click)="cart.add('Book')">Add book</button>`,
})
export class ProductListComponent {
cart = inject(CartService);
}
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `<span>Items: {{ cart.items().length }}</span>`,
})
export class CartBadgeComponent {
cart = inject(CartService);
}Clicking the button never changes the badge. The symptom is "the count stays at zero". Nothing in the console reports an error.
Debug it with the Injector Tree.
- Open the Injector Tree tab and find the node for
ProductListComponent. - Select it and read the provider list.
CartServiceappears in the list of that element injector. - Select the node for
CartBadgeComponent. Its own list has noCartService, so it resolves the token further up the path, in the root environment injector. - Select the root environment injector and confirm that it holds a separate
CartService.
Two injectors own a CartService, so there are two instances. Removing providers: [CartService] from ProductListComponent fixes the bug, because both components then resolve the single root instance. After the fix, reload and check the tree again. The element injector node should no longer list the service.
providers versus viewProviders
An element injector can register tokens in two ways, and the difference affects which nodes can see them.
| Registration | Visible to the component's template | Visible to projected content (`<ng-content>`) |
|---|---|---|
| `providers` | Yes | Yes |
| `viewProviders` | Yes | No |
A provider registered with viewProviders is hidden from content that a parent projects into the component. If projected content gets a different instance than the component's own template does, look at the provider list of the component's node. The list shows which of the two arrays holds the token. Then check whether the failing consumer sits inside the component's view or inside projected content.
Environment injectors and lazy routes
Routes can declare their own providers. Angular creates an environment injector for the route when it is activated, and it is a child of the injector that was active when the route was configured. A lazy-loaded route that provides a service therefore holds its own copy, separate from the root one.
In the Injector Tree you can spot this in two steps.
- Navigate to the lazy route in your app so Angular creates its injector.
- Reopen or refresh the Injector Tree and look for an environment injector node between the root and your component.
If the node is missing, the route hasn't been activated yet or its injector wasn't created. If a service appears in both the route injector and the root injector, components under the route get the route's copy, and components outside it get the root copy.
Checking resolution from the console
The ng global gives you the same information from the console. It works with an element you selected in the Elements panel ($0).
// Select the <app-cart-badge> element in the Elements panel first.
const badgeInjector = ng.getInjector($0);
console.log(badgeInjector);
// Select the <app-product-list> element, then compare:
const listInjector = ng.getInjector($0);
console.log(listInjector);ng.getInjector returns the injector associated with the element. You can pass it a component instance, a directive instance, or a DOM element. Calling .get(Token) on the result resolves the token the same way Angular would. This works only if the token is reachable from your code. The class must be exposed to the console, for example by assigning it to window temporarily during a debugging session.
import { CartService } from './cart.service';
// Temporary debugging aid. Remove before committing.
(window as unknown as { CartService: typeof CartService }).CartService = CartService;Then compare the two instances in the console.
// Run once with <app-product-list> selected, store the result:
const a = ng.getInjector($0).get(CartService);
// Select <app-cart-badge> and run:
const b = ng.getInjector($0).get(CartService);
console.log(a === b); // false means two instances existA result of false confirms what the Injector Tree showed. The console check is useful when you want proof that two consumers share an instance, or when you want to call a method on the service and watch the UI react.
Common errors and how to read them
| Symptom | Likely cause | What to check in the Injector Tree |
|---|---|---|
| `NullInjectorError: No provider for X` | No injector on the lookup path has a provider for `X` | Select the failing node and walk the path up. No node should list `X`. Add the provider at the right level |
| State not shared between components | A component or route re-provides a root service | Find nodes other than the root that list the service |
| Projected content gets a different instance | The provider is in `viewProviders` | Compare the provider list of the host component with the consumer's location |
| A service seems to reset on navigation | The provider lives on a route or component that is destroyed and recreated | Check whether the injector node disappears when you leave the route |
| A service is missing from the root list | It is `providedIn: 'root'` and has not been requested yet | Use it in the app first, then refresh the view |
Limits of this tool
- DevTools shows what is registered, not why a given class asked for a token. For that, read the constructor or
inject()calls in the source. - Tokens created with
InjectionTokenappear under the name you gave them as the description. Give each token a clear description so the list is readable. - Values supplied through
useValueoruseFactoryappear as providers, but the Injector Tree doesn't show how a factory computes its result. Use the console or a breakpoint for that. - The tool needs a development build. In a production build the debugging information is not available.
Exercise
A SettingsService is declared with providedIn: 'root'. A ThemePanelComponent also lists SettingsService in its providers array. Changing a setting in the panel doesn't update the header, which injects the same service. Describe how you would confirm the cause with Angular DevTools, and what you would change.
Show answer
Open the Injector Tree tab and select the node for ThemePanelComponent. Its provider list shows SettingsService, so the panel has its own element-level instance. Then select the header's node, which lists no SettingsService, and follow its path up to the root environment injector. The root injector holds a second, separate instance. The header and the panel therefore use different objects. To fix it, remove SettingsService from the component's providers array so both resolve the root instance. Reload, and check that the component's node no longer lists the service.