Sub topic 4
Injecting Services with inject() and Constructors
This chapter assumes you know TypeScript classes and access modifiers, standalone components, and the CartService from the previous chapter, which uses @Injectable({ providedIn: 'root' }). Here you ask Angular for that service in two ways: with the inject() function and with constructor parameters.
The two forms
Both forms ask the current injector for the instance registered under a token, here the CartService class. Angular creates the instance once at root level and hands the same object to every consumer.
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);
}
// Equivalent constructor injection:
// constructor(protected readonly cart: CartService) {}When you use the constructor form, Angular reads the parameter's type from metadata the compiler emits and resolves it the same way. The template can read cart because it is protected and not private. Templates can access public and protected members only.
Services injecting services
Services use the same mechanism. A CheckoutService can depend on CartService and on Angular's HttpClient. HttpClient needs provideHttpClient() among your bootstrap providers.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CartService } from './cart.service';
@Injectable({ providedIn: 'root' })
export class CheckoutService {
private readonly http = inject(HttpClient);
private readonly cart = inject(CartService);
submit() {
return this.http.post('/api/orders', { count: this.cart.count() });
}
}Choosing between them
| Concern | `inject()` | Constructor parameter |
|---|---|---|
| Subclassing | The subclass doesn't have to pass anything to `super()` | The subclass must repeat every parameter and pass it to `super(...)` |
| Use in functions | Works in factories, guards, and resolvers | Classes only |
| Type metadata | Not needed | Needs a real runtime import of the type |
| Options (`optional`, `skipSelf`) | Passed as an object argument | Needs parameter decorators such as `@Optional()` |
The Angular team now recommends inject(). Constructor injection still works fully, and you will see it in older code.
Common errors
Calling inject() too late
inject() only works while Angular is constructing the class. That covers field initializers and the constructor body. If you call it in a lifecycle hook or an event handler, Angular throws NG0203: inject() must be called from an injection context.
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({ selector: 'app-bad', standalone: true, template: '' })
export class BadComponent implements OnInit {
private cart?: CartService;
ngOnInit(): void {
this.cart = inject(CartService); // throws NG0203
}
}The fix is to move the call into a field initializer. A later chapter covers the full rules and runInInjectionContext.
Type-only imports with constructors
If you write import type { CartService }, TypeScript erases the import, and the constructor parameter loses its runtime token. Use a normal import. inject(CartService) avoids the problem because it passes the class as a value.
Field order
Field initializers run from top to bottom. If one field uses an injected service, declare the injected field above it:
protected readonly cart = inject(CartService);
protected readonly label = `Cart (${this.cart.count()})`;Exercise
A developer moves inject(CartService) from a field initializer into a click handler onClick(), and the app throws NG0203. Why, and what is the smallest fix?
Show answer
inject() only works in an injection context, which means during construction (field initializers, the constructor, or provider factories). A click handler runs later, outside that context. The fix is to inject the service in a field, private readonly cart = inject(CartService);, and use this.cart inside onClick().
Exercise
You have class Base { constructor(protected cart: CartService) {} } and a subclass that needs an extra Logger. Write the subclass using inject() for both dependencies, without a constructor.
Show answer
Base becomes class Base { protected readonly cart = inject(CartService); } and the subclass becomes class Child extends Base { private readonly logger = inject(Logger); }. Neither class needs a constructor, so the subclass doesn't have to pass anything to super().