Key takeaway
- Angular dependency injection for v22: services, inject(), providers, injection tokens, hierarchical injectors and testing, with a decision table.
Angular dependency injection (DI) is the mechanism that hands a class the objects it needs, instead of the class creating them itself. You mark a class as a service, ask for it with the inject() function, and Angular's injector finds or creates the instance for you. That keeps components small, lets you swap a real service for a stub in tests, and gives a team one consistent way to share code.
Modern Angular has changed how DI is written. Current angular.dev documentation teaches inject() and the @Service decorator, and shows providers at application, route and component level, where older guides centred on NgModule and constructor parameters. This guide covers the parts that matter for architects and platform leads on the current release, Angular v22. If you are still choosing a framework, start with our Angular vs React learning path.
What is dependency injection in Angular?
The Angular documentation describes DI as a design pattern for organising and sharing code across an application, built on two actions: you provide a value, and you inject it. A class that needs an HTTP client or a data store does not construct one. It declares the need, and the framework supplies the instance. Five roles take part.
| Role | What it is | Example |
|---|---|---|
| Consumer | The component, directive, service or guard that needs a dependency | A navigation bar component |
| Dependency | The service or value being requested | An analytics logger |
| Injection token | The key that identifies the dependency; a class can act as its own token | The class AnalyticsLogger, or an InjectionToken for a non-class value |
| Provider | The recipe that tells Angular how to create the value for a token | useClass, useValue, useFactory, useExisting |
| Injector | The object that holds providers, resolves a token and returns the instance | The application's environment injector |
Why use dependency injection in Angular?
The business case is change and testing. A class that builds its own HTTP client cannot be tested without a real backend, and cannot be pointed at a different implementation at runtime. A class that receives its dependencies can be given a stub in a unit test, a different implementation per environment, or a newer version of a shared service, without edits to the consumer.
- Loose coupling: the consumer knows what it needs, not how it is built.
- Easier testing: tests replace a dependency through providers, as shown later in this guide.
- Reuse: a component works with any implementation that honours the same contract.
How do you create and inject a service in Angular v22?
The creating and using services guide shows a service as a TypeScript class decorated with @Service(), which makes it available across the application as a singleton. The guide describes @Service as an ergonomic shorthand for the traditional @Injectable({providedIn: 'root'}), so existing @Injectable services remain valid.
import {Service} from '@angular/core';
@Service()
export class BasicDataStore {
private data: string[] = [];
addData(item: string): void {
this.data.push(item);
}
getData(): string[] {
return [...this.data];
}
}
A consumer then requests the service with inject(), usually in a field initialiser:
import {Component, inject} from '@angular/core';
import {BasicDataStore} from './basic-data-store';
@Component({
selector: 'app-example',
template: '<button (click)="dataStore.addData(\'More data\')">Add</button>',
})
export class Example {
dataStore = inject(BasicDataStore);
}
One limit to know before you migrate: the same guide states that @Service supports only inject() and does not support constructor-based injection. Keep @Injectable where you need constructor injection or the provider options that @Service replaces with its factory function. The main DI overview also shows inject() being used in route guards, not only in classes.
How do providers and injection tokens work?
Automatic provision covers most services. When you need to choose the implementation, or inject something that is not a class, you write a provider. The dependency provider reference lists four value types.
| Provider option | What it does | When it fits |
|---|---|---|
useClass |
Creates an instance of the class you name | Swapping a real service for a mock or alternative implementation |
useValue |
Supplies a fixed value | Configuration such as an API URL |
useFactory |
Calls a function to build the value, optionally with deps |
A value that depends on other injected configuration |
useExisting |
Aliases one token to another existing one | Renaming a service without breaking consumers |
The documentation notes that useClass creates separate instances, while useExisting ensures you receive the same singleton. For values that are not classes, such as configuration, functions or primitives, create an InjectionToken. Angular identifies tokens by object reference, so the description string is only for debugging.
export const API_URL = new InjectionToken<string>('api.url');
bootstrapApplication(AppComponent, {
providers: [{provide: API_URL, useValue: 'https://api.example.com'}],
});
Setting multi: true on a provider lets several providers share one token, and injecting that token returns an array of all the instances. Angular's own provideRouter and provideHttpClient follow the provideX function pattern that library authors export for consumers.
Where should you provide a service?
The provider's location decides its lifetime and who can see it. Pick the narrowest scope that works.
| Where | Lifetime and visibility | When it fits |
|---|---|---|
@Service() or providedIn: 'root' |
One shared instance for the whole application | Default for shared services; the docs also note tree-shaking |
providers in application config |
Global singleton, always bundled | HTTP, logging and global configuration |
providers on a route |
Available to components and directives in that route | Feature-specific and lazy-loaded features |
providers on a component or directive |
New instance per component, destroyed with it | State that belongs to one component |
The trade-off is stated in the docs: application-level providers are always bundled and are harder to customise per feature, while route and component providers keep state local. NgModule providers arrays are the older route to the same goal, and new code does not need them. For the performance side of structuring features, see our guide to Angular performance optimisation.
How does hierarchical dependency injection resolve a dependency?
Older guides describe two hierarchies, components and modules. The hierarchical injectors guide names them differently: the EnvironmentInjector hierarchy, configured through @Service() or the providers array in ApplicationConfig, and the ElementInjector hierarchy, created implicitly at each DOM element and empty unless a component or directive sets providers.
- Angular searches the ElementInjector hierarchy, starting at the requesting element and moving up through its parents.
- If the token is not found, it checks the EnvironmentInjector hierarchy.
- If it still finds nothing, it throws an error. At the top of the tree sits the NullInjector, which always throws unless you asked for the dependency as optional.
When the same token is provided at several levels, the first provider Angular meets wins. You can steer the search with resolution modifiers passed to inject(), for example inject(FlowerService, {skipSelf: true}).
| Modifier | Effect |
|---|---|
optional |
Resolves to null instead of throwing when no provider is found |
self |
Looks only at the ElementInjector of the current component or directive |
skipSelf |
Starts the search at the parent injector |
host |
Makes the host component the last stop in the search |
One more distinction for component authors: providers makes a service visible to the component, its content and its children, while viewProviders limits visibility to the component's own view, so projected content cannot see it.
Where can you call inject()?
The injection context guide explains that inject() works only while code runs in a context where the current injector is available. That includes constructors and field initialisers of classes created by DI, useFactory functions, InjectionToken factory functions, and functions that Angular runs in a context, such as router guards. Calling it elsewhere, for example inside a click handler, throws error NG0203. When you must call it later, runInInjectionContext runs a function inside an injector you hold, such as the EnvironmentInjector.
How do you test code that uses dependency injection?
The testing services guide uses TestBed to set up an isolated injection environment, then retrieves the service under test with TestBed.inject(). To test a service without its real collaborator, provide a stub for that token.
TestBed.configureTestingModule({
providers: [{provide: TaxCalculator, useValue: taxCalculatorStub}],
});
service = TestBed.inject(OrderTotal);
The guide injects a fresh instance in beforeEach, so each test starts clean. The same replace-through-providers idea scales up: swap an HTTP-facing service for a stub and no network is needed. For wider guidance on structuring components, see reusable Angular components and the Angular coding style guide.
What has changed in Angular DI, and which versions are supported?
| Older advice | Current documentation |
|---|---|
| Declare dependencies as constructor parameters | Examples use inject(); constructor injection needs @Injectable rather than @Service |
@Injectable({providedIn: 'root'}) on every service |
@Service() is the shorthand; @Injectable remains valid |
Register services in an NgModule providers array |
Provide at root, in application config, on a route or on a component |
| Two hierarchies: components and modules | ElementInjector and EnvironmentInjector hierarchies |
On support, the Angular releases page lists v22 as the active release since 3 June 2026, with long-term support to June 2028. v21 and v20 are in long-term support, with v20 support ending on 28 November 2026, and versions 2 to 19 are no longer supported. Plan any DI migration against that calendar.
When should you not rely on component-level providers?
Component-level providers create a new instance for every component, so they are the wrong tool for state that several parts of the page must share. Application-level providers are the opposite: they are always bundled, so keep them for genuinely global services. A practical adoption sequence for a team:
- Default new shared services to
@Service()orprovidedIn: 'root'and consume them withinject(). - Introduce
InjectionTokenfor configuration instead of hard-coded strings or imported constants. - Move feature-only services to route providers as features are lazy loaded.
- Write tests that replace dependencies through
TestBedproviders before refactoring older constructor-based code. - Migrate
@Injectableservices to@Serviceonly where constructor injection and advanced provider options are not needed.
The same principle, depending on a replaceable contract rather than a concrete implementation, applies to AI agent tooling. ElixirClaw is an agentic OS platform to build, orchestrate and govern AI agents and automation workflows while keeping humans in control, and ElixirData Context OS keeps governed context, versioned policy and decision traces in one decision layer above AI agents. If your front-end team still maintains legacy code, our AngularJS development services page describes what we offer.
To map one front-end or delivery decision your agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.
Frequently asked questions about Angular dependency injection
What is dependency injection in Angular?
It is a pattern where Angular supplies a class with the services it needs. You provide a value, then request it with inject(), and the injector returns the instance instead of the class creating it.
Should I use inject() or constructor injection?
The current docs use inject() in their examples. The @Service decorator supports only inject(), so use @Injectable if you need constructor injection.
What does providedIn root do?
It provides the service at the root level, giving one shared instance for the application and allowing unused services to be tree-shaken. @Service() is a shorthand for @Injectable({providedIn: 'root'}).
Why do I get error NG0203?
You called inject() outside an injection context. Call it in a constructor, field initialiser or factory function, or use runInInjectionContext with an injector you hold.
How do I replace a dependency in a unit test?
Add a provider for the token in TestBed.configureTestingModule, for example {provide: TaxCalculator, useValue: stub}, then retrieve the service under test with TestBed.inject().
Next Steps with Angular Dependency Injection
Talk to our experts about implementing compound AI system, How Industries and different departments use Agentic Workflows and Decision Intelligence to Become Decision Centric. Utilizes AI to automate and optimize IT support and operations, improving efficiency and responsiveness.
Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.
Explore the XenonStack platform family: ElixirData · ElixirClaw · ElixirHub · NexaStack · MetaSecure · Neural AI · AgentGRC · AgentSRE · AgentAnalyst · AgentInstruct · AgentRAI · AgentScrum · AgentSearch · AgentForce · AI Aviator · SAIF Aviator · CohortIQ · XenonStack AI · XenonStack UAE