Sub topic 1
What dependency injection gives you in Angular
Prerequisites
This chapter assumes you already know the following:
- TypeScript classes, decorators and basic generics.
- Standalone components in Angular and how to declare a component with
@Component. - How to write a simple service class and use it from a component.
- How routes are configured in a
Routesarray.
You do not need to know anything about injector hierarchies yet. This chapter sets up the vocabulary that the rest of the tutorial builds on.
The problem dependency injection solves
A component often needs help from other objects. It may need an HTTP client, a logger, a settings store or a shared counter. The simplest approach is to create those objects yourself:
import { Component } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-badge',
standalone: true,
template: `<span>{{ counter.count() }}</span>`,
})
export class BadgeComponent {
protected readonly counter = new CounterService();
}This code works, but it has three costs:
- Sharing is accidental. Every
BadgeComponentcreates its ownCounterService. If you wanted one shared counter, you must pass the same object around by hand. - Testing is hard. The component creates its own service, so a test cannot swap in a fake.
- Coupling grows. If
CounterServicelater needs its own dependencies, every place that callsnew CounterService()must change.
Dependency injection (DI) is a pattern where a class declares what it needs, and a separate piece of code supplies those objects. In Angular, that separate piece of code is the injector. An injector is an object that knows how to create or find instances of dependencies and hands them to the classes that ask for them.
What Angular's DI gives you
Angular's DI system provides four practical benefits.
- Shared instances. One service instance can serve the whole application.
- Scoped instances. A service can instead be tied to a route or to one component, so each scope gets its own copy.
- Replaceable implementations. The class that asks for a dependency does not decide which implementation it gets. A test, a route or a parent component can supply a different one.
- Lazy creation. Angular creates a service instance the first time something asks for it, not at startup.
The second benefit is the reason this tutorial exists. The word "hierarchical" in the title means that injectors form a tree, and the position of a provider in that tree decides which code sees which instance.
The three terms: token, provider, injector
Every DI lookup involves three things.
| Term | Meaning | Example |
|---|---|---|
| Token | The key used to ask for a dependency. | The class `CounterService`, or an `InjectionToken` |
| Provider | A recipe that tells an injector how to produce a value for a token. | `{ provide: API_URL, useValue: '/api' }` |
| Injector | The object that holds providers and creates values on request. | The root environment injector |
A token is usually a class, because a class exists at runtime and can be used as a key. When the thing you want to inject is not a class, such as a string or a configuration object, you create an InjectionToken. A later chapter covers tokens and provider recipes in detail. For now, remember that a lookup always has the form "injector, find me a value for this token".
Your first shared service
The simplest way to register a service is the providedIn: 'root' option on @Injectable:
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly count = signal(0);
increment(): void {
this.count.update(n => n + 1);
}
}This tells Angular to register a provider for CounterService in the root environment injector. The root environment injector is the injector created when the application starts, and every part of the application can reach it. As a result, there is only one CounterService instance in the whole application.
A component asks for the service with the inject() function:
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter-button',
standalone: true,
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterButtonComponent {
protected readonly counter = inject(CounterService);
}If you place two CounterButtonComponent elements on a page, both buttons show the same number. Clicking either one changes both, because both components received the same instance.
The same service, one instance per component
Sharing is not always what you want. Suppose each counter button should keep its own count. You do not have to change the service. You change where it is provided:
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter',
standalone: true,
providers: [CounterService],
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterComponent {
protected readonly counter = inject(CounterService);
}The providers array on the component registers CounterService with the injector that belongs to that component's element. Each time Angular creates a CounterComponent, it also creates a new injector entry and, on first use, a new CounterService. Two CounterComponent elements now show independent counts.
The class CounterService and the inject(CounterService) call are identical in both examples. Only the place where the provider is declared changed. That is the core idea of hierarchical DI: the consumer asks for a token, and the surrounding injector tree decides which instance answers.
A first look at the tree
Angular keeps two connected hierarchies of injectors:
- Environment injectors are tied to the application, to routes and to NgModules. The root environment injector is the best known.
- Element injectors are tied to elements in the DOM tree, one for each component or directive that declares providers.
When a component asks for a token, Angular searches the element injectors from the component upward through its parents. If none of them has a provider, it continues into the environment injectors. If nothing provides the token, you get a NullInjectorError.
This is a simplified picture. The chapters on the two hierarchies and the resolution algorithm refine it, including how route providers fit in and how the lookup options change the search. What matters now is the order: the component's own scope first, then outward.
Why this matters in practice
Knowing where a provider lives lets you predict behavior and avoid common bugs.
| Situation | Where to provide | Result |
|---|---|---|
| Logger, HTTP wrapper, auth state | `providedIn: 'root'` | One instance for the whole app |
| Settings used only by an admin area | Route `providers` | One instance for that route's components |
| Form state, selection state, widget state | Component `providers` | One instance per component |
| A fake service in a test | Test overrides | The test controls the instance |
A frequent mistake is to put a service in a component's providers array and then expect other components to see its state. They will not, because they sit outside that component's injector. The reverse mistake is also common. A developer registers a service in the root and is surprised that two parts of the page share state they expected to be separate.
You can often tell which situation you are in by asking one question: "Which injector holds the provider that answers this lookup?" The rest of this tutorial teaches you how to answer it.
Constructor injection and `inject()`
Older Angular code uses constructor parameters to request dependencies:
import { Component } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-legacy-counter',
standalone: true,
template: `{{ counter.count() }}`,
})
export class LegacyCounterComponent {
constructor(protected readonly counter: CounterService) {}
}Angular reads the parameter type and uses it as the token. This behaves exactly like inject(CounterService). The inject() function is the style used in this tutorial because it works in field initializers, in plain functions such as route guards, and with the lookup options introduced in a later chapter. Both styles ask the same injector tree.
What to take away
- DI separates "what a class needs" from "which instance it gets".
- A token names the dependency, a provider says how to build it, and an injector holds providers and answers lookups.
- Where you declare a provider decides the sharing: root for one instance per application, a route for one per route, a component for one per component.
- Lookups start at the closest scope and move outward, and a missing provider ends in
NullInjectorError.
Exercise
Two <app-counter> elements are on a page. The component lists CounterService in its own providers, and CounterService is also marked providedIn: 'root'. Do the two counters share a count? Explain which injector answers each lookup.
Show answer
No. Each CounterComponent has its own element injector with a CounterService provider, and a lookup checks the component's own injector before the root environment injector. So each component gets a separate instance and the root instance is never used by these two. The counts are independent.
Exercise
A developer calls inject(CounterService) inside a button's click handler and gets an error. Why, and how should the code change?
Show answer
inject() only works in an injection context, and an event handler runs outside one. The fix is to call inject(CounterService) in a field initializer or constructor, store it in a field, and use that field in the click handler.