Sub topic 2
How Dependency Injection Works
This chapter assumes you know TypeScript classes and constructors, how Angular components are declared, and basic ES module imports. The previous chapter covered why services exist. This one explains how Angular gets a service instance into the code that needs it.
The problem with `new`
Suppose CartApi needs an HTTP helper. Without dependency injection, the class builds its own helper:
class HttpHelper {
get(url: string): string {
return `GET ${url}`;
}
}
class CartApi {
private readonly http = new HttpHelper();
load(): string {
return this.http.get('/cart');
}
}
console.log(new CartApi().load()); // GET /cartThis causes three problems:
CartApiis tied to one concreteHttpHelper, so a test can't hand it a fake.- Each
CartApigets its ownHttpHelper, which means instances can't share state. - When
HttpHelpergains a dependency of its own, every place that callsnewhas to change.
Dependency injection (DI) is a design pattern where a class declares what it needs and something outside the class supplies it. In Angular, that outside party is the injector.
The three parts of DI
Angular's DI system has three parts:
| Part | What it is | Example |
|---|---|---|
| Token | The key that identifies a dependency | The `CartApi` class itself |
| Provider | A recipe that tells the injector how to create the value for a token | "Construct `CartApi` with an `HttpHelper`" |
| Injector | The container that holds providers, creates instances, and caches them | The application's root injector |
A consumer asks for a token. The injector finds the matching provider, builds the value (resolving that value's own dependencies first), stores it, and returns it. Later requests for the same token get the cached instance, so one injector holds one instance per token.
Seeing the injector directly
In application code you rarely touch an injector yourself. To see how one works, you can create a standalone injector with Injector.create. This version lists each dependency explicitly in deps:
import { Injector } from '@angular/core';
class HttpHelper {
get(url: string): string {
return `GET ${url}`;
}
}
class CartApi {
constructor(private readonly http: HttpHelper) {}
load(): string {
return this.http.get('/cart');
}
}
const injector = Injector.create({
providers: [
{ provide: HttpHelper, useClass: HttpHelper, deps: [] },
{ provide: CartApi, useClass: CartApi, deps: [HttpHelper] }
]
});
const first = injector.get(CartApi);
const second = injector.get(CartApi);
console.log(first.load()); // GET /cart
console.log(first === second); // trueCartApi no longer calls new. It states that it needs an HttpHelper and gets one. Swapping the provider for HttpHelper changes what every consumer receives, and you don't have to edit CartApi.
In a real app, the @Injectable decorator and the compiler work out the deps list for you. The next chapters cover that.
Common errors
NullInjectorError: No provider for X: no injector in the lookup path has a provider for the token. Usually the service was never registered, or a provider was left out of a test setup.- Expecting a fresh instance on each request: within one injector, a token resolves to a single cached instance. To get separate instances, register the provider in a different injector. Later chapters on the injector hierarchy show how.
- Circular dependency errors (
NG0200): A needs B and B needs A, so neither can be built first. Move the shared logic into a third service.
Exercise
In the Injector.create example, you add a third provider, { provide: CartSummary, useClass: CartSummary, deps: [CartApi] }, and call injector.get(CartSummary) after the two existing get calls. How many HttpHelper instances exist in total, and why?
Show answer
One. The injector already created and cached HttpHelper when it first resolved CartApi. CartSummary gets the cached CartApi, which holds that same HttpHelper, so no new instance is created.
Exercise
A test calls injector.get(CartApi) on an injector whose only provider is for CartApi, with deps: [HttpHelper]. What happens?
Show answer
Resolution fails with a NullInjectorError for HttpHelper. The injector can find CartApi's recipe, but it has no provider for HttpHelper, so it cannot build the dependency.