Sub topic 4
Injecting Services with inject() and Constructors
A service that nobody can reach is useless. This chapter covers the two ways a class asks Angular for a dependency: the inject() function and constructor parameters. You will learn how each one works, where each one is allowed to run, and the errors you will hit most often.
This chapter assumes you know TypeScript classes and generics, standalone Angular components, and the CartService built in the previous chapter with @Injectable({ providedIn: 'root' }).
The two injection styles
Both styles ask the same injector for the same thing. Only the syntax differs. Here is the CartService from the previous chapter, which the examples below consume:
// cart.service.ts
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly items = signal<string[]>([]);
readonly count = computed(() => this.items().length);
add(item: string): void {
this.items.update(list => [...list, item]);
}
}A component can receive it with inject() in a field initializer:
// cart-badge.component.ts
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.count() }}`
})
export class CartBadgeComponent {
protected readonly cart = inject(CartService);
}The same component can also receive it through a constructor parameter property:
// cart-badge.component.ts (constructor style)
import { Component } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.count() }}`
})
export class CartBadgeComponent {
constructor(protected readonly cart: CartService) {}
}In both cases Angular uses CartService as the lookup key, which is called the token. It walks the injector hierarchy until it finds a provider for that token, then hands back the instance. Because the service is providedIn: 'root', every consumer gets the same singleton.
How constructor injection finds the token
TypeScript types disappear at runtime, so how does Angular know the parameter wants CartService? The Angular compiler reads the constructor signature at build time. It generates a factory function that calls the injector for each parameter type. A class name works as a token because classes exist at runtime as JavaScript values. Interfaces and type aliases do not exist at runtime, so they cannot serve as tokens.
When the parameter type is not a usable token, you name the token explicitly with @Inject(). The built-in DOCUMENT token is a common case:
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-title-setter',
standalone: true,
template: ''
})
export class TitleSetterComponent {
constructor(@Inject(DOCUMENT) private readonly doc: Document) {
this.doc.title = 'Shop';
}
}With inject(), the token is just the argument, and the return type comes from the token's generic type:
import { Component, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-title-setter',
standalone: true,
template: ''
})
export class TitleSetterComponent {
private readonly doc = inject(DOCUMENT); // typed as Document
constructor() {
this.doc.title = 'Shop';
}
}Custom tokens with InjectionToken are covered in a later chapter. The pattern is the same: inject(TOKEN) or @Inject(TOKEN).
When injection is allowed
inject() has no object to read from. It reads the "current injector" that Angular sets while it constructs a class. That window is called the injection context. For components, directives, pipes, and services, the context is open during:
- field initializers
- the constructor body
- factory functions used by providers (
useFactory,providedInfactories) - functional guards, resolvers, and HTTP interceptors, which Angular calls inside a context
Lifecycle hooks, event handlers, setTimeout callbacks, and subscribe callbacks run later, after the context has closed.
Constructor injection never runs into this problem, because constructor parameters are always resolved at construction time. That rule is the main source of one of the common errors below.
Comparing the styles
| Aspect | `inject()` | Constructor parameters |
|---|---|---|
| Where the token appears | Function argument | Parameter type, or `@Inject(token)` |
| Works with inheritance | Base class injects its own fields | Subclass must accept and forward deps via `super()` |
| Usable outside classes | Yes, in guards, interceptors, factories, helper functions | No |
| Type inference for tokens | From the token's generic | You write the type yourself |
| Options (optional, self, etc.) | Options object: `{ optional: true }` | Decorators: `@Optional()`, `@Self()` |
| Current Angular docs and schematics | Default style | Still fully supported |
Angular's documentation and ng generate output now use inject(). You can convert an existing project with the migration schematic ng generate @angular/core:inject. Both styles can coexist in one codebase, and the two produce the same instance.
Inheritance without forwarding
Constructor injection makes base classes awkward. Every subclass has to repeat the parent's dependencies and pass them to super():
import { Component, Directive } from '@angular/core';
import { CartService } from './cart.service';
@Directive()
export abstract class CartAwareBase {
constructor(protected readonly cart: CartService) {}
}
@Component({
selector: 'app-checkout-button',
standalone: true,
template: `<button (click)="cart.add('gift card')">Add ({{ cart.count() }})</button>`
})
export class CheckoutButtonComponent extends CartAwareBase {
constructor(cart: CartService) {
super(cart);
}
}If the base class later gains a new dependency, every subclass breaks. With inject(), the base class owns its dependencies:
import { Component, Directive, inject } from '@angular/core';
import { CartService } from './cart.service';
@Directive()
export abstract class CartAwareBase {
protected readonly cart = inject(CartService);
}
@Component({
selector: 'app-checkout-button',
standalone: true,
template: `<button (click)="cart.add('gift card')">Add ({{ cart.count() }})</button>`
})
export class CheckoutButtonComponent extends CartAwareBase {}The @Directive() decorator on the abstract base is required. Without it, Angular does not generate the metadata it needs for the inherited members.
Reusable injection helpers
Because inject() is a plain function, you can wrap it in your own functions. The wrapper inherits the caller's injection context:
// cart-count.ts
import { Signal, inject } from '@angular/core';
import { CartService } from './cart.service';
export function injectCartCount(): Signal<number> {
return inject(CartService).count;
}import { Component } from '@angular/core';
import { injectCartCount } from './cart-count';
@Component({
selector: 'app-mini-badge',
standalone: true,
template: `{{ count() }}`
})
export class MiniBadgeComponent {
protected readonly count = injectCartCount();
}The inject prefix tells readers that the helper must be called in an injection context, the same as inject() itself.
Passing options
inject() takes an optional second argument that changes how lookup behaves. The most common option is optional, which returns null instead of throwing when no provider exists. TypeScript narrows the return type to match:
import { inject } from '@angular/core';
import { CartService } from './cart.service';
export function injectCartIfPresent(): CartService | null {
return inject(CartService, { optional: true });
}The constructor equivalent is the @Optional() parameter decorator. The full set of options (optional, self, skipSelf, host) gets its own chapter later.
Common errors
NG0203: inject() called outside an injection context
This is the error you will hit most often with inject():
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-broken',
standalone: true,
template: ''
})
export class BrokenComponent implements OnInit {
ngOnInit(): void {
const cart = inject(CartService); // throws NG0203 at runtime
cart.add('apple');
}
}The fix is to inject in a field and use the field later:
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-fixed',
standalone: true,
template: ''
})
export class FixedComponent implements OnInit {
private readonly cart = inject(CartService);
ngOnInit(): void {
this.cart.add('apple');
}
}If you really need to resolve something lazily, inject the Injector itself and use runInInjectionContext, which a later chapter covers.
NG0201: No provider found
inject(SomeService) or a constructor parameter of type SomeService throws NG0201 when no injector in the chain has a provider. Usually the service is missing providedIn: 'root', or it is meant to be provided by a component or route that is not an ancestor of the consumer. The error message lists the injector path Angular searched, which tells you where it looked.
Interface used as a constructor type
// Does not work: AppSettings is an interface, so no runtime token exists
// constructor(private settings: AppSettings) {}The compiler reports that it cannot resolve the parameter. Use a class or an InjectionToken, together with @Inject() or inject().
NG0200: Circular dependency
If A injects B and B injects A, Angular cannot construct either one. Switching from constructors to inject() does not fix this, because both run at construction time. Break the cycle by moving the shared logic into a third service, or by injecting Injector and resolving one side only when it is needed.
Field order matters
Field initializers run top to bottom. A field that uses an injected service must come after the field that injects it:
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-ordered',
standalone: true,
template: `{{ count() }}`
})
export class OrderedComponent {
private readonly cart = inject(CartService);
protected readonly count = this.cart.count; // fine: cart is already set
}If you swap those two lines, this.cart is undefined when count is initialized, and the component throws a TypeError.
Exercise
A teammate writes ngAfterViewInit() { this.doc = inject(DOCUMENT); } and sees NG0203. Explain why, and rewrite it so it works.
Show answer
ngAfterViewInit runs after construction, when the injection context has closed, so inject() has no current injector. Move the call into a field initializer: private readonly doc = inject(DOCUMENT);, and use this.doc inside ngAfterViewInit.
Exercise
An abstract base directive uses constructor(protected cart: CartService) {}. You add a second dependency, DOCUMENT, to the base. What changes in each of five subclasses, and how would inject() avoid it?
Show answer
Every subclass constructor must add a @Inject(DOCUMENT) doc: Document parameter and pass it to super(cart, doc). If the base declares protected readonly cart = inject(CartService); and protected readonly doc = inject(DOCUMENT); as fields, subclasses need no constructor and nothing changes in them.
Exercise
What does inject(CartService, { optional: true }) return, and what is its TypeScript type, when no provider for CartService exists?
Show answer
It returns null instead of throwing NG0201, and its type is CartService | null, so the compiler makes you handle the null case.