Sub topic 3
Requesting Dependencies with inject() and Constructors
This chapter assumes you know TypeScript classes and decorators, can write a standalone Angular component, and have used a service in a component before. It covers the two ways a class asks Angular for a dependency, where each one works, and the errors you will meet when you use them wrongly. The injector hierarchy that answers the request comes in later chapters.
Two ways to ask for a dependency
A class never creates its own dependencies. It declares what it needs, and the injector that creates the class supplies those objects. Angular offers two syntaxes for the declaration:
- Constructor parameter injection, where the type of each constructor parameter is the token to look up.
- The
inject()function, which you call during construction and which returns the dependency for a token you pass in.
Both ask the same injector the same question. The difference is in how you write the request and where you are allowed to make it.
Constructor parameters
With constructor injection, Angular reads the parameter types and looks each one up as a token.
import { Component } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter',
standalone: true,
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterComponent {
constructor(protected readonly counter: CounterService) {}
}The class type CounterService is both the TypeScript type and the runtime token. Angular's compiler records the parameter types in the class metadata. This only works for tokens that exist at runtime, so classes work and interfaces do not. An interface is erased at compile time, so it cannot be a token.
For tokens that are not classes, such as an InjectionToken<string>, constructor injection needs the @Inject parameter decorator:
import { Component, Inject } from '@angular/core';
import { API_URL } from './tokens';
@Component({
selector: 'app-api-info',
standalone: true,
template: `{{ url }}`,
})
export class ApiInfoComponent {
constructor(@Inject(API_URL) protected readonly url: string) {}
}The inject() function
inject() takes the token directly, and the return type follows from the token.
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter',
standalone: true,
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterComponent {
protected readonly counter = inject(CounterService);
}The field initializer runs while the instance is being constructed, so inject() is legal there. Because the token is an ordinary argument, the same call works for class tokens and InjectionToken values without extra decorators:
import { Component, inject } from '@angular/core';
import { API_URL } from './tokens';
@Component({
selector: 'app-api-info',
standalone: true,
template: `{{ url }}`,
})
export class ApiInfoComponent {
protected readonly url = inject(API_URL);
}Here url is typed as string because API_URL is an InjectionToken<string>.
Comparing the two syntaxes
| Aspect | Constructor parameters | `inject()` |
|---|---|---|
| Token for a class | The parameter type | The class passed as an argument |
| Token for an `InjectionToken` | Needs `@Inject(TOKEN)` | Passed directly, typed automatically |
| Modifiers (optional, self, and so on) | Parameter decorators such as `@Optional()` | An options object |
| Subclassing | Subclass must repeat all parent parameters and call `super(...)` | Parent fields initialize themselves, and the subclass needs no extra code |
| Usable outside constructors | No | Yes, in any injection context |
| Field initializers can use the dependency | Only through `this` inside the constructor body | Yes |
The subclassing row deserves a closer look. With constructor injection, adding a dependency to a base class changes its constructor signature, so every subclass must be edited. With inject(), the base class holds the dependency in a field and subclasses are untouched. The Angular style guide recommends inject() for new code for this reason.
The injection context
inject() does not work everywhere. It only works in an injection context, which is a stretch of synchronous code during which Angular has made a particular injector the current one. You are in an injection context when:
- A class is being constructed by an injector, including its field initializers and constructor body. This covers components, directives, pipes, services, and
NgModuleclasses. - A provider factory runs, such as a
useFactoryfunction or thefactoryof anInjectionToken. - A function-style route guard, resolver, or HTTP interceptor runs.
- Code runs inside
runInInjectionContext(injector, fn). - An initializer such as
provideAppInitializerruns.
Calling inject() anywhere else throws an error such as NG0203: inject() must be called from an injection context. The usual causes are calling it inside a lifecycle hook, an event handler, a setTimeout callback, or after an await.
import { Component, inject, OnInit } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-broken',
standalone: true,
template: ``,
})
export class BrokenComponent implements OnInit {
ngOnInit(): void {
// Throws NG0203: construction has finished, so there is no injection context.
const counter = inject(CounterService);
counter.increment();
}
}The fix is to call inject() in a field initializer and keep the result:
import { Component, inject, OnInit } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-fixed',
standalone: true,
template: ``,
})
export class FixedComponent implements OnInit {
private readonly counter = inject(CounterService);
ngOnInit(): void {
this.counter.increment();
}
}Helper functions that call inject()
Because the context is tied to the call stack and not to a class, you can wrap inject() in a plain function and call that function from a constructor or field initializer. This is how Angular's own functions such as inject(ActivatedRoute) wrappers and many community utilities are built.
import { inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
export function injectRouteParam(name: string): string | null {
return inject(ActivatedRoute).snapshot.paramMap.get(name);
}A component then writes protected readonly id = injectRouteParam('id');. The helper is only valid when called from an injection context, so name such functions with an inject prefix to signal the rule.
Running code later with runInInjectionContext
When you need to call an inject()-based function after construction, capture the injector and re-enter the context:
import { Component, EnvironmentInjector, inject } from '@angular/core';
import { runInInjectionContext } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-later',
standalone: true,
template: `<button (click)="run()">Run</button>`,
})
export class LaterComponent {
private readonly injector = inject(EnvironmentInjector);
run(): void {
runInInjectionContext(this.injector, () => {
inject(CounterService).increment();
});
}
}Injecting Injector (or EnvironmentInjector) and calling injector.get(Token) is a simpler option when you only need one lookup and no helper functions.
Modifiers in both syntaxes
Chapter later in this tutorial explains what each modifier does to the lookup. Here is how you spell them in each style, so the notation is familiar.
| Modifier | Constructor decorator | `inject()` option |
|---|---|---|
| optional | `@Optional()` | `{ optional: true }` |
| self | `@Self()` | `{ self: true }` |
| skipSelf | `@SkipSelf()` | `{ skipSelf: true }` |
| host | `@Host()` | `{ host: true }` |
import { Component, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-badge',
standalone: true,
template: ``,
})
export class BadgeComponent {
protected readonly theme = inject(ThemeService, { optional: true });
}With optional: true, the type of theme becomes ThemeService | null. TypeScript then forces you to handle the missing case. The constructor form @Optional() theme: ThemeService | null requires you to write the | null yourself, and nothing checks that you did.
Dependencies that are not available yet
inject() returns a ready value, so the dependency must be creatable at that moment. Two situations cause trouble:
- Circular dependencies. If
AinjectsBin its field initializer andBinjectsA, Angular reportsNG0200: Circular dependency in DI detected. Break the cycle by injectingInjectorin one class and callinginjector.get(A)later, when it is needed. - Optional lookups that return
null. Check fornullbefore use, or Angular will not help you at runtime.
What happens when a lookup fails
If no provider is found and the request is not optional, Angular throws NullInjectorError: No provider for CounterService!. The error comes from the same place in both syntaxes. It does not mean the syntax was wrong. It means the walk through the injectors ended without finding a provider. The later chapters on resolution and pitfalls show how to follow that walk.
Choosing between them
Use inject() in new code. It gives better typing for tokens, works with inheritance, and lets you build reusable helper functions. Keep constructor injection when you maintain a codebase that already uses it consistently, since mixing styles inside one class adds noise without benefit. Do not rewrite working constructors only for style.
One practical check: when you write a unit test that constructs a class by hand with new, constructor injection lets you pass fakes as arguments. A class that uses inject() cannot be built that way, and you create it through TestBed.inject or runInInjectionContext instead. Later chapters on testing cover this.
Exercise
A component calls inject(CounterService) inside its ngOnInit method and Angular throws NG0203. Why does it fail, and what are two ways to fix it?
Show answer
ngOnInit runs after construction has finished, so no injection context is active. One fix is to move the call to a field initializer (private readonly counter = inject(CounterService);) and use this.counter in ngOnInit. The other is to inject EnvironmentInjector (or Injector) in a field, then call runInInjectionContext(this.injector, () => inject(CounterService)) or this.injector.get(CounterService) inside ngOnInit.
Exercise
You write constructor(private url: API_URL_TYPE) {} where API_URL_TYPE is type API_URL_TYPE = string and the provider uses an InjectionToken<string>. Why does this not work, and how do you fix it with each syntax?
Show answer
A type alias or interface is erased at compile time, so it cannot act as a runtime token, and string is not the token that was provided. With constructor injection, use constructor(@Inject(API_URL) private url: string) {}. With inject(), write private readonly url = inject(API_URL);, which is typed as string from the token.