Sub topic 13
Common pitfalls and debugging NullInjectorError
This chapter assumes you know how providers and injection tokens work. It also assumes you know the two injector hierarchies: environment injectors (root and route) and element injectors (one per component or directive). The goal is to turn the errors and surprises that come from this model into a short checklist you can apply.
Reading a NullInjectorError
The most common failure looks like this:
NullInjectorError: R3InjectorError(Standalone[AdminComponent])[AdminSettingsService -> AdminSettingsService]:
NullInjectorError: No provider for AdminSettingsService!Newer Angular versions also print the code NG0201. Read the message in three parts:
- The text in parentheses,
Standalone[AdminComponent], names where the lookup started. - The arrow chain,
A -> B -> C, shows the dependency path. The last name is the token that had no provider. Earlier names are the classes that asked for it. - "No provider for X" means the walk reached the end of both hierarchies and found nothing, with no
optionalflag to soften the result.
Angular already walked every injector it could reach from the starting point. So the real question is: from this starting point, which injectors could see a provider?
Pitfall 1: The provider is in a branch the requester cannot see
Lookups only travel upward. An element injector sees its own providers and those of its ancestors. It never sees providers on children or siblings. A service listed in providers on <app-sidebar> is invisible to <app-header>, even though both live in the same app.
The same rule applies to environment injectors. A route's providers live in an environment injector that is a child of the root. Anything running in the root injector cannot see into it:
import { Injectable, inject } from '@angular/core';
@Injectable()
export class AdminSettingsService {
readonly pageSize = 25;
}
@Injectable({ providedIn: 'root' })
export class AuditService {
// Fails with NullInjectorError: AuditService is built in the root injector,
// which cannot see providers declared on the 'admin' route.
private readonly settings = inject(AdminSettingsService);
}Note that it does not matter that an admin component requested AuditService. A providedIn: 'root' service is always created in the root injector. The fix is one of these:
- Provide
AdminSettingsServiceat the root too, if it needs to be global. - Move
AuditServiceinto the route'sprovidersso both live in the same injector. - Pass the value as a method argument instead of injecting it.
Pitfall 2: Two instances where you expected one
Duplicate instances produce no error. State simply fails to be shared. Common causes:
- A service is
providedIn: 'root'and also listed in a component'sproviders. The component gets its own copy, and everything else gets the root one. - A service is listed in
providersof a component that appears many times. Each instance of the component gets a separate service. This is the intended scoping behavior from earlier in the tutorial, but it surprises people who copied aprovidersarray from an example. - The same service is listed in the
providersof two different routes. Each route gets its own environment injector, so each gets its own instance. - A lazy-loaded route or module lists a service that the root already provides. Code in the lazy area gets a second instance.
To check which instance you have, give the service a temporary id:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly id = Math.random().toString(36).slice(2, 7);
}Log counter.id from the components you suspect. If the ids differ, search the codebase for every providers array that mentions the class.
Pitfall 3: The opposite problem, a shared instance you wanted to be separate
If two components unexpectedly share state, the service is probably provided higher up than you thought. Check for providedIn: 'root' on the class. That one is easy to forget when the class was written by someone else. A service with providedIn: 'root' and no providers entry on your component is a singleton. Add the service to the component's providers to give each component instance its own copy.
Pitfall 4: Projected content and viewProviders
A provider in viewProviders is visible to the component's template children. It is not visible to content projected through <ng-content>. If a service in viewProviders is requested by a projected component, the lookup skips it and continues to the ancestors. The result is either a different instance or a NullInjectorError. Switch to providers if projected content must see the service, or keep viewProviders on purpose to hide it.
Pitfall 5: Resolution modifiers that contradict the setup
Modifiers narrow the search. They are a frequent source of "it worked until I added self":
| Option | Effect | Typical mistake |
|---|---|---|
| `self: true` | Looks only in the requester's own injector | The provider is on the parent, so it throws |
| `skipSelf: true` | Starts at the parent injector | Expecting your own `providers` entry to count |
| `host: true` | Stops at the host element of the current component | The provider is above the host, so it is not found |
| `optional: true` | Returns `null` instead of throwing | The code later dereferences `null` |
Be careful with optional. It does not fix a missing provider. It moves the failure from startup to the first line that uses the value. Use it only when the dependency really is optional, and type the field with | null so the compiler makes you check.
Pitfall 6: Tokens that do not exist at runtime
TypeScript interfaces disappear at compile time, so they cannot be tokens. Writing inject(MyInterface) fails to compile. Use an abstract class or an InjectionToken:
import { InjectionToken, inject } from '@angular/core';
export interface AppConfig {
apiUrl: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
// In a component or service:
// private readonly config = inject(APP_CONFIG);A token created without a factory has no default. If nobody lists it in providers, you get NullInjectorError: No provider for InjectionToken APP_CONFIG!. The string description you pass to the constructor is what appears in the message, so make it specific.
Also remember that two new InjectionToken('X') calls with the same description are different tokens. Identity is by object reference. If you import the token from two paths that are really two copies of the file, for example through a duplicated library build, providers will not match.
Pitfall 7: Calling inject() outside an injection context
inject() only works while Angular is constructing something: in a field initializer, a constructor, a factory function, or a few framework hooks such as route guards. Calling it inside a setTimeout or an event handler throws NG0203. Capture what you need first, or run the code in a saved context:
import { Injectable, Injector, inject, runInInjectionContext } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(message: string): void {
console.log(message);
}
}
@Injectable({ providedIn: 'root' })
export class DeferredWork {
private readonly injector = inject(Injector);
runLater(): void {
setTimeout(() => {
const logger = runInInjectionContext(this.injector, () => inject(LoggerService));
logger.log('ran later');
});
}
}Often simpler: inject LoggerService as a field and use it inside the callback. Use runInInjectionContext only when the dependency choice itself happens late.
Pitfall 8: Circular dependencies
If A injects B and B injects A, Angular reports NG0200 with the cycle in the message. Moving the code between classes does not remove the cycle. Break it by extracting the shared logic into a third service, or by injecting Injector and calling injector.get(A) lazily when the call is needed.
A debugging procedure
- Read the arrow chain in the error and identify the token and the class that asked for it.
- Find where the requester is created: component tree, route, or root. This decides its starting injector.
- Search for every place the token is provided:
providedIn,providerson components, directives and routes, andbootstrapApplicationorApplicationConfig. - Check whether any of those providers lies on the upward path from step 2.
- Check for modifiers on the
inject()call that cut the path short. - If it still fails, probe at runtime with
inject(Injector).get(Token, null)in the suspect component and compare the result with other places.
The Angular DevTools extension has an injector tree view. It shows the element and environment injectors and the providers in each, which makes steps 3 and 4 visual.
Exercises
Exercise
A providedIn: 'root' service ReportService injects FilterState, which is listed only in the providers of the /reports route. A component under /reports injects ReportService. Why does this throw NullInjectorError, and what are two fixes?
Show answer
ReportService is created in the root injector, which cannot see providers in the route's child environment injector, so FilterState is not found. Fixes: provide ReportService in the same route's providers (so both live in the route injector), or provide FilterState at the root if it should be global. Passing the filter as a method argument also works.
Exercise
Two sibling components each list CartService in providers, yet both are meant to show the same cart. They show different items. Why, and how do you fix it?
Show answer
Each component's providers entry creates a separate element injector instance of CartService. Remove it from both components and use providedIn: 'root', or provide it once on a common ancestor component so both siblings resolve to the ancestor's instance.
Exercise
A component calls inject(LoggerService) inside a click handler and gets NG0203. What is wrong, and what is the simplest fix?
Show answer
inject() is only valid in an injection context, such as a field initializer or constructor. A click handler runs later, outside that context. Move the call to a field (private readonly logger = inject(LoggerService);) and use the field in the handler.