Sub topic 3
Requesting dependencies with inject() and constructors
This chapter assumes you know TypeScript classes and decorators, standalone components, and how to write a basic Angular service. It covers the two ways a class asks Angular for a dependency. Later chapters cover which injector answers the request.
Two ways to ask
A class declares what it needs, and Angular supplies it when it creates the class. You can declare a need in a constructor parameter or by calling inject().
import { Component, inject } 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 = inject(CounterService);
}The constructor version produces the same result:
import { Component } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-badge-ctor',
standalone: true,
template: `<span>{{ counter.count() }}</span>`,
})
export class BadgeCtorComponent {
constructor(protected readonly counter: CounterService) {}
}In the constructor version, Angular reads the parameter type and uses the class CounterService as the token. A token is the key Angular uses to look up a provider. For a token that is not a class, such as an InjectionToken, add @Inject(API_URL) to the parameter. With inject() you pass the token directly: inject(API_URL).
The injection context
inject() only works in an injection context, a moment when Angular is creating something and has an injector ready. These places qualify:
- A constructor.
- A field initializer.
- A provider factory, such as the
factoryof anInjectionTokenor auseFactoryfunction. - A function called from any of those places.
Calling inject() anywhere else, for example inside a click handler, throws error NG0203. Call it once during construction and store the result in a field.
Reusing logic in helper functions
Because inject() is an ordinary function, you can wrap it in your own helper. Constructor parameters cannot do this.
import { inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
export function routeParam(name: string): string | null {
return inject(ActivatedRoute).snapshot.paramMap.get(name);
}A component can then write readonly id = routeParam('id'); as a field initializer. The helper works because the field initializer runs in the injection context.
If you must call such a helper from code that runs outside the injection context, wrap the call with runInInjectionContext:
import { Injector, runInInjectionContext } from '@angular/core';
export function readId(injector: Injector): string | null {
return runInInjectionContext(injector, () => routeParam('id'));
}Choosing between them
| Concern | Constructor parameters | `inject()` |
|---|---|---|
| Inheritance | A subclass must repeat the parent's parameters and pass them to `super()`. | A subclass inherits the parent's fields without a constructor. |
| Reusable helpers | Not possible. | Any function in the injection context can call it. |
| Non-class tokens | Needs `@Inject(TOKEN)`. | Pass the token directly. |
| Lookup options | Decorators such as `@Optional()` and `@Self()`. | An options object, for example `{ optional: true }`. |
New Angular code usually prefers inject(), and the rest of this tutorial uses it. Both styles use the same injector tree and give the same result.
Common errors
- NG0203:
inject()ran outside an injection context. Move the call into a field initializer or the constructor. - NullInjectorError: no injector in the lookup path has a provider for the token. Check where the provider is declared.
Exercise
A component has a method onSave() that calls inject(NotificationService) and then uses the service. Why does this fail at runtime, and how do you fix it?
Show answer
onSave() runs after construction, in a click handler, so there is no injection context and Angular throws NG0203. Fix it by declaring private readonly notifications = inject(NotificationService); as a field and using this.notifications inside onSave().