Skip to content

Dependency Injection in Angular

Dependency injection is the part of Angular most developers use constantly and understand least. inject(SomeService) works, so the questions stop there — until something does not work, and the error is NG0201: No provider for X, or two components mysteriously share state they should not, or a service that should be a singleton is instantiated four times.

Every one of those is a question about which injector answered the request. DI in Angular is not a bag of singletons; it is two intersecting trees with well-defined lookup rules. Learn the rules and the errors stop being mysterious.

  • Injector — an object that maps tokens to values, with a parent it can delegate to.
  • Token — the key you look up: a class, an InjectionToken, or (historically) a string.
  • Provider — the recipe telling an injector how to produce a value for a token.
  • Injection context — a runtime state in which the “current injector” is set, and inject() therefore works.
  • EnvironmentInjector — the application-level tree: root, route injectors, platform.
  • ElementInjector — created implicitly at every DOM element; configured by providers / viewProviders on a component or directive.
  • Tree-shakable provider — one declared on the service (@Service() / providedIn: 'root') rather than in a providers array, so a bundler can drop it if unused.

Two trees, searched in a fixed order.

NullInjector ← throws, or returns null with { optional: true }
↑
platform EnvironmentInjector ← DomSanitizer and friends
↑
root EnvironmentInjector ← @Service(), providedIn: 'root', ApplicationConfig providers
↑
route EnvironmentInjectors ← Route.providers, lazy-loaded features
↑
┌─────────────────────┴─────────────────────┐
│ ElementInjector tree (mirrors the DOM) │ ← component/directive `providers`
└───────────────────────────────────────────┘

When a component or directive asks for a token, Angular resolves it in two phases:

  1. Walk up the ElementInjector hierarchy from the requesting element.
  2. If not found, return to the originating element and walk up the EnvironmentInjector hierarchy.

If it is still not found, Angular throws.

Two consequences worth internalising:

  • The first provider found wins. A provider on the component itself shadows everything above it. This is the mechanism behind per-component service instances — and behind “why is my singleton not a singleton.”
  • The ElementInjector tree follows the DOM, not your file structure. A service provided on a component is visible to everything rendered inside it, including components you did not write.
import { Service, inject } from '@angular/core';
@Service()
export class OrderApiClient {
private readonly http = inject(HttpClient);
getOrder(id: string) {
return this.http.get<Order>(`/api/orders/${id}`);
}
}
@Component({ /* ... */ })
export class OrderDetail {
private readonly api = inject(OrderApiClient);
}

No providers array anywhere. @Service() registers the class in the root EnvironmentInjector, and because the registration lives on the class rather than in a list, a bundler can tree-shake it if nothing injects it.

@Service() is the modern shorthand for @Injectable({ providedIn: 'root' }). It is not a full replacement:

Requirement @Service @Injectable
inject() function Yes Yes
Constructor-based DI No Yes
Implicit root singleton Yes Needs { providedIn: 'root' }
useClass / useValue / useExisting / useFactory No — single factory option Yes
Non-root scopes ('platform') No Yes

Reach for @Service() for a new singleton that uses inject(). Keep @Injectable() when you need constructor injection, an advanced provider key, or a non-root scope.

@Service() accepts two options. factory controls how the singleton is built and runs in an injection context, so inject() works inside it:

@Service({
factory: () => (inject(ANALYTICS_ENABLED) ? new RemoteAnalytics() : new Analytics()),
})
export class Analytics {
track(event: string, payload?: Record<string, unknown>): void {
// No-op by default.
}
}

And autoProvided: false opts out of automatic root registration, so you can scope the class to a route or component yourself:

@Service({ autoProvided: false })
export class WizardState { /* ... */ }

inject() only works where Angular has set a current injector. You are in an injection context:

  • During the constructor of a DI-instantiated class.
  • In field initialisers of such classes.
  • In a useFactory function of a provider or @Injectable.
  • In the factory of an InjectionToken or a @Service.
  • In any stack frame running inside an injection context.

That last one is what makes functional router guards, resolvers and interceptors work:

export const canActivateTeam: CanActivateFn = (route, state) =>
inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);

Angular runs the guard inside an injection context, so inject() is legal in the function body.

The single most common DI error in modern Angular:

export class OrderDetail {
private readonly api = inject(OrderApiClient); // fine — field initialiser
ngOnInit(): void {
const logger = inject(Logger); // NG0203 — lifecycle hooks are not injection contexts
}
}

Lifecycle hooks, event handlers, and setTimeout callbacks are not injection contexts. Move the inject() call to a field initialiser.

When you genuinely need to run something in a context later, capture an injector and re-enter:

@Service()
export class ReportRunner {
private readonly injector = inject(EnvironmentInjector);
run(): void {
runInInjectionContext(this.injector, () => {
const exporter = inject(ReportExporter);
exporter.export();
});
}
}

Use it sparingly. Nine times in ten, capturing the dependency in a field is simpler and clearer. It earns its place for dynamically-created components and for library code that must run user-supplied callbacks in a context.

If you write a helper that calls inject(), assert the precondition so callers get a message naming your function rather than a generic DI error:

export function injectNativeElement<T extends Element>(): T {
assertInInjectionContext(injectNativeElement);
return inject(ElementRef).nativeElement;
}

This is the polite thing to do in any shared “custom inject function,” which is otherwise a booby trap for whoever calls it from ngOnInit.

Four options change where the search starts and stops. All are passed as the second argument to inject().

Modifier Effect
optional: true Resolve to null instead of throwing when not found
self: true Look only at the current element’s ElementInjector
skipSelf: true Start at the parent ElementInjector
host: true Stop searching at the host component

They combine freely except for two illegal pairs: host + self, and skipSelf + self.

// Only if this element itself provides it; null otherwise.
readonly leaf = inject(LeafService, { optional: true, self: true });
// Deliberately get the parent's instance, ignoring our own provider.
readonly parentTheme = inject(ThemeService, { skipSelf: true });

Each has a real use:

  • optional — for genuinely optional collaborators, and for feature detection (“is a form control container present above me?”).
  • self — for a directive that must be paired with a provider on the same element. Combine with optional so a missing pairing gives null rather than an exception you have to catch.
  • skipSelf — the classic recursive-component escape hatch: a component that provides a service for its children but needs the parent’s instance for itself.
  • host — bounds the search at the host component, which matters for content-projection scenarios where you do not want to reach past the component you were projected into.

Constructor injection has the decorator equivalents @Optional(), @Self(), @SkipSelf(), @Host(). Same semantics; prefer the inject() options in new code.

Both configure a component’s ElementInjector. The difference is exactly one thing:

viewProviders are visible only inside the component’s own template. Content projected in through <ng-content> cannot see them.

@Component({
selector: 'orders-panel',
providers: [PanelTelemetry], // visible to the view AND to projected content
viewProviders: [PanelLayout], // visible only to the view
template: `<ng-content />`,
})
export class OrdersPanel {}

This is a real design tool, not a footnote. providers says “anything rendered inside my element can use this.” viewProviders says “this is my private implementation detail, and I do not want to accidentally satisfy a projected component’s dependency with it.” Library components should reach for viewProviders for internal collaborators, because a consumer’s projected content resolving against your internals is a coupling nobody intended.

Interfaces do not exist at runtime, so they cannot be DI tokens. InjectionToken gives you a unique object reference to use instead:

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
export const FEATURE_FLAGS = new InjectionToken<Readonly<Record<string, boolean>>>('FEATURE_FLAGS');

The string argument is a debugging description only — Angular identifies the token by object reference, not by that string. Two tokens with the same description are two different tokens.

Tokens can carry their own tree-shakable factory:

export const WINDOW = new InjectionToken<Window>('Window', {
providedIn: 'root',
factory: () => window,
});

That is the idiomatic way to make platform globals injectable — and therefore substitutable in tests, which is the actual point.

Recipe Use for
{ provide: T, useClass: Impl } Swap an implementation, keep DI-constructed
{ provide: T, useValue: v } Configuration objects, constants, test doubles
{ provide: T, useFactory: fn, deps: [...] } Value that depends on runtime conditions
{ provide: T, useExisting: Other } Alias — same instance under a second token

useExisting is the one people forget, and it is the correct tool when a class should be reachable under both its concrete type and an abstract token without creating two instances. useClass on an already-provided class creates a second instance; useExisting aliases the first.

Several providers contributing to one token, injected as an array:

export const VALIDATION_RULES = new InjectionToken<readonly Rule[]>('VALIDATION_RULES');
providers: [
{ provide: VALIDATION_RULES, useClass: RequiredFieldsRule, multi: true },
{ provide: VALIDATION_RULES, useClass: DateRangeRule, multi: true },
];

Injecting VALIDATION_RULES yields both. This is the extension-point pattern: a feature can contribute behaviour without the consuming code knowing about it. One rule with teeth — a token is either always multi or never multi. Mixing the two forms for the same token is a runtime error.

OrdersPortal needs an API client whose base URL differs per environment, a per-route service scoped to a lazy feature, and a per-component instance for an editable row.

tokens.ts
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
// api-client.ts
@Service()
export class OrderApiClient {
private readonly http = inject(HttpClient);
private readonly baseUrl = inject(API_BASE_URL);
list() {
return this.http.get<Order[]>(`${this.baseUrl}/orders`);
}
}
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideRouter(routes),
{ provide: API_BASE_URL, useValue: 'https://api.example.test/v1' },
],
};
// orders.routes.ts — a route-scoped injector
export const ordersRoutes: Routes = [
{
path: 'orders',
providers: [OrdersFeatureState], // one instance for this route subtree
loadComponent: () => import('./orders-portal').then((m) => m.OrdersPortal),
children: [
{ path: ':id', loadComponent: () => import('./order-detail').then((m) => m.OrderDetail) },
],
},
];
// order-row.ts — a per-component instance
@Component({
selector: 'order-row',
providers: [OrderRowEditor], // one editor per row, not one for the app
template: `...`,
})
export class OrderRow {
private readonly editor = inject(OrderRowEditor);
}

Three different lifetimes, three different mechanisms, and the choice of mechanism is the lifetime decision:

  • API_BASE_URL in ApplicationConfig: one value, whole app, configured at bootstrap so it can come from the build environment.
  • OrdersFeatureState in Route.providers: one instance shared by every screen under orders, invisible to the rest of the app. By default it is not destroyed when the user navigates away — the route’s injector stays alive — so if the state must reset on leaving, reset it explicitly (or opt in to injector cleanup; see below).
  • OrderRowEditor in the component’s providers: one instance per rendered row, destroyed with the row. Getting this wrong — putting it in root — is the classic bug where editing one row edits them all.

Tokens are keys, and InjectionToken is a unique object. DI is a Map lookup with a parent pointer. Class tokens work because the class object is the key — which is why two copies of the same library in node_modules produce two distinct tokens and the famously confusing “No provider for HttpClient” when HttpClient is obviously provided.

Tree-shakable providers invert the registration. providedIn: 'root' writes a static ɵprov field onto the class carrying its factory. The injector, on a miss, asks the token itself whether it knows how to make one. Because nothing references the class from a central list, a bundler can drop it. A providers: [X] array is a real reference and always retains X.

ElementInjectors are not objects per element. Creating a real injector for every DOM node would be ruinous. Angular stores provider metadata in the view’s data structures and resolves by walking that, so an element with no providers costs essentially nothing.

NullInjector is the terminator. It is the parent of the platform injector and its only behaviour is to throw. { optional: true } catches that and yields null. This is why “no provider” errors surface at the top of the tree rather than at the point of the mistake.

Instances are cached on the injector that created them. A root-provided service resolved from a deeply nested component is stored on the root injector, not the component’s — so it is genuinely shared, and it lives as long as the root injector does.

Modern Angular libraries do not export providers arrays; they export functions returning EnvironmentProviders. You have used them: provideRouter(), provideHttpClient(), provideAnimationsAsync().

export interface OrdersConfig {
readonly baseUrl: string;
readonly pageSize?: number;
}
export function provideOrders(config: OrdersConfig): EnvironmentProviders {
return makeEnvironmentProviders([
{ provide: API_BASE_URL, useValue: config.baseUrl },
{ provide: ORDERS_PAGE_SIZE, useValue: config.pageSize ?? 25 },
OrderApiClient,
]);
}

Why this is better than exporting a providers array:

  • A typed, discoverable API. Consumers get autocomplete and compile-time errors rather than assembling tokens by hand.
  • Internals stay internal. You can add, rename or remove a token without a breaking change, because nobody outside referenced it.
  • Composable features. The provideHttpClient(withInterceptors([...]), withXsrfConfiguration({...})) shape lets optional capabilities be tree-shaken when not requested.
  • EnvironmentProviders cannot be used in a component’s providers array. The type system enforces that application-level configuration is applied at application level — a genuine class of misconfiguration eliminated at compile time.

If you ship anything reusable inside your organisation, ship it as a provideX() function.

providers on a component is the cleanest way to express “this state belongs to this component instance.” A wizard’s step state, a row editor, a drag-and-drop session, a chart’s interaction state: none of these should be root singletons, and none of them need manual cleanup if they are component-provided, because Angular destroys the injector with the component.

The trade-off is discoverability. A service provided three components up is invisible at the point of injection — nothing in inject(WizardState) tells you which instance you get. Keep such services narrowly named and document the intended provision point on the class itself.

Route.providers creates a child EnvironmentInjector for the route subtree. Combined with loadComponent / loadChildren, that is how a feature gets both its own code chunk and its own service instances.

Be precise about what that buys you. A route injector controls visibility and instance identity — which code can inject the service, and that all screens in the subtree share one instance. It does not, by default, control lifetime: Angular does not destroy a route’s injector when the user navigates away, so a route-provided service keeps its state and its subscriptions until the application ends.

If you need the injector torn down when its routes are no longer in use, opt in with withAutoCleanupInjectors() in provideRouter(...) (public API from Angular v22.2; earlier releases exposed it as withExperimentalAutoCleanupInjectors(), now deprecated). It destroys the injectors of inactive routes that the RouteReuseStrategy is not storing. A custom strategy that does not extend BaseRouteReuseStrategy must implement shouldDestroyInjector() and report any stored handles via retrieveStoredRouteHandles(). When “reset on leaving” is a product requirement, the most explicit design is still to reset the state yourself — for example from the feature’s root component’s DestroyRef.

DI is the reason Angular code is testable at all. TestBed.configureTestingModule({ providers: [...] }) builds an injector where you substitute anything:

TestBed.configureTestingModule({
providers: [
{ provide: API_BASE_URL, useValue: 'https://test.example.test' },
{ provide: OrderApiClient, useValue: fakeOrderApi },
],
});

And TestBed.overrideComponent(OrderRow, { set: { providers: [{ provide: OrderRowEditor, useValue: fake }] } }) replaces a component-level provider, which you cannot reach from the root providers array. See the testing guide for the full treatment.

Everything in root. @Service() is the easy default, and it is right most of the time — but a service holding state that belongs to one screen should not outlive that screen. Root-scoped mutable state is how you get stale data after navigation and cross-tab bleed in multi-instance UIs.

inject() in a lifecycle hook or event handler. NG0203. Move it to a field initialiser.

String tokens. { provide: 'apiUrl', useValue: ... } has no type safety and collides silently across an application. Use InjectionToken<T>.

useClass where useExisting was meant. Providing the same class under two tokens with useClass gives you two instances and a very confusing bug — state written through one token is invisible through the other.

Injecting a service to reach a service. inject(FeatureFacade).someOtherService.method() couples you to the facade’s internals. Inject what you need.

Exporting a providers array from a library. Every token becomes public API. Export a provideX() function.

A concrete class where an abstraction was wanted. If a component injects HttpOrderApiClient rather than an abstract OrderApiClient, you cannot substitute it without touching the component. Depend on the abstraction and provide the implementation. Do not over-apply this — an interface with exactly one implementation and no test double is ceremony — but do apply it at genuine seams.

Circular dependencies between services. A depends on B depends on A gives a runtime error or undefined. It is a design smell: extract the shared concern into a third service, or invert one direction with an event or a signal.

Error / symptom Meaning Fix
NG0201: No provider for X Search reached NullInjector Provide it, or add { optional: true } if genuinely optional
NG0203: inject() must be called from an injection context Called from a hook, handler, or callback Move to a field initialiser, or runInInjectionContext
NG0200: Circular dependency detected A ↔ B Extract a third service or invert one edge
Singleton behaves as multiple instances A providers array shadows the root provider Search for the class name in providers arrays
Two components share state that should be separate Provided too high Move the provider onto the component
Injected value is undefined Field-initialiser ordering, or a circular dependency Check declaration order; check for a cycle
“No provider” for something clearly provided Duplicate library copies → two distinct class tokens npm ls <package>; dedupe
Projected content cannot see a provider It is in viewProviders Move it to providers if projection should see it

A reliable diagnostic technique: when a “no provider” error makes no sense, inject the injector itself and ask it what it knows.

private readonly injector = inject(Injector);
ngOnInit(): void {
console.log(this.injector.get(OrderApiClient, 'NOT FOUND'));
}

Injector.get with a default value tells you whether the token is reachable from that point in the tree, which localises the problem to a level rather than leaving it as “somewhere.”

DI is not usually a hot path, but three effects are real.

Tree-shakability is the big one. @Service() / providedIn: 'root' lets unused services leave the bundle. A providers array in ApplicationConfig retains everything it names, whether or not the running code path uses it. Prefer the tree-shakable form; use ApplicationConfig for things that must exist regardless.

Eagerness. Root services are created on first injection, not at bootstrap — so an expensive constructor costs nothing until something asks. But a provider listed in ApplicationConfig that other bootstrap providers depend on is constructed during bootstrap, and expensive work there is on the critical path to first paint. Push it into a lazily-injected service or an APP_INITIALIZER-style hook that can complete asynchronously.

Instance count. A component-provided service in a list of 1,000 rows means 1,000 instances plus their injectors. That is usually correct and usually cheap — but it is worth knowing when a row-level service starts holding subscriptions or observers.

Two DI-specific points.

Configuration injected at bootstrap ends up in the client bundle. An InjectionToken holding an API base URL or a feature flag is fine. One holding an API secret is a published secret — anyone can read it in the built JavaScript. Values that must stay secret belong on a server the client calls, never in a provider.

A DI-provided permission service is a UI convenience, not an authorisation boundary. inject(Permissions).canEdit() decides whether to render a button. It does not stop anyone calling the endpoint. Every authorisation decision must be enforced server-side. Guards and permission services improve the experience of legitimate users; they protect nothing.

Decision Favours Costs
@Service() / root Simple, tree-shakable, one instance State lives for the application’s lifetime
Route.providers Feature-scoped visibility; one instance per feature Not destroyed on navigation by default; reset explicitly or opt in to withAutoCleanupInjectors()
Component providers Per-instance state, automatic cleanup Invisible at the injection site
InjectionToken over class token Works for non-class values; explicit Extra indirection to trace
Abstract token + useClass Substitutable, testable Ceremony when there is only ever one implementation
provideX() function Typed API, hidden internals, composable More library code to write
inject() over constructor params Works in functions, inheritance-friendly, terser Requires an injection context; less obvious to newcomers

“Walk me through what happens when a component calls inject(SomeService).” Angular resolves in two phases. First it walks up the ElementInjector hierarchy from the requesting element — the component’s own providers, then each ancestor component’s, following the rendered DOM structure rather than the file structure. If no ElementInjector provides the token, it returns to the originating element and walks up the EnvironmentInjector hierarchy: route injectors, then root, then platform, then NullInjector, which throws. First match wins, and the created instance is cached on whichever injector produced it.

“Two sibling components unexpectedly share state. Where do you look?” At where the service is provided. If it is @Service() or providedIn: 'root', there is one instance for the whole application by design, and it needs to move to the component’s providers (per-instance) or Route.providers (per-feature). The inverse bug — one component per instance where a singleton was intended — has the same root cause read the other way: someone added the class to a component’s providers array, which shadows the root provider for that whole subtree.

“When would you use viewProviders instead of providers?” When the service is an internal collaborator that projected content must not resolve against. providers is visible to everything rendered inside the element, including content projected through <ng-content> from a consumer who knows nothing about your internals. viewProviders restricts visibility to the component’s own template. For a reusable component with <ng-content>, that distinction prevents a whole category of accidental coupling.

“Why do libraries export provideX() instead of a providers array?” Type safety and encapsulation. A function takes a typed config object and returns EnvironmentProviders, so the tokens involved stay private and can change without a breaking release. It also enables the composable-feature pattern (provideHttpClient(withInterceptors([...]), withXsrfConfiguration({...}))), where unrequested capabilities tree-shake away. And EnvironmentProviders is deliberately not assignable to a component’s providers array, so the type system prevents application-level configuration from being applied at the wrong level.

“You get NG0203 from code that looks correct. What is happening?” inject() was called outside an injection context — most often in ngOnInit, an event handler, a setTimeout, or after an await. Contexts are the constructor, field initialisers, provider and token factories, and frames running inside one (which is why functional guards work). The fix is normally to move the call to a field initialiser. Where the call genuinely must happen later, capture an EnvironmentInjector and use runInInjectionContext.

“Everything is provided in root. Is that a problem?” Not for stateless collaborators — API clients, formatters, loggers — where a singleton is correct and tree-shaking still applies. It is a problem for anything holding mutable, screen-specific state, which then survives navigation, leaks between users of a long-lived tab, and cannot be reset without an explicit teardown method somebody will forget to call. The lifetime question — “when should this be destroyed?” — should drive the design: component providers are destroyed with the component; route providers are not destroyed on navigation unless you opt in to withAutoCleanupInjectors(); root means “never.”