Services and dependency injection
Components render. Services do everything else. Angular's injector decides which instance each component receives — and that seam is what makes the whole application testable.
A service
import { computed, inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({ providedIn: 'root' }) // one instance for the whole app
export class AuthService {
private readonly router = inject(Router);
private readonly api = inject(AuthApi);
private readonly token = signal<string | null>(
localStorage.getItem('token'));
readonly isAuthenticated = computed(() => this.token() !== null);
readonly claims = computed(() => decodeJwt(this.token()));
readonly roles = computed(() => this.claims()?.roles ?? []);
hasRole(role: string): boolean {
return this.roles().includes(role);
}
async login(email: string, password: string): Promise<void> {
const { accessToken } = await this.api.login(email, password);
localStorage.setItem('token', accessToken);
this.token.set(accessToken);
}
logout(): void {
localStorage.removeItem('token');
this.token.set(null);
this.router.navigate(['/login']);
}
currentToken(): string | null {
return this.token();
}
}
If nothing injects the service, it is removed from the bundle entirely. That is why it is
preferred over listing services in a providers array — which always ships
them.
inject() vs the constructor
// classic — still perfectly valid
export class OrderListComponent {
constructor(
private readonly store: OrderStore,
private readonly router: Router,
) {}
}
// modern — no constructor, works in field initialisers
export class OrderListComponent {
private readonly store = inject(OrderStore);
private readonly router = inject(Router);
// and it composes: a reusable function that injects
readonly orders = this.store.orders;
}
// inject() also works inside standalone FUNCTIONS,
// which is what makes functional guards and interceptors possible
export const adminGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.hasRole('ADMIN') || router.createUrlTree(['/forbidden']);
};
That means field initialisers, constructors, factory functions, guards, interceptors and
effect() callbacks. Calling it inside ngOnInit or an event
handler throws NG0203. If you must defer, capture inject(Injector)
first and use runInInjectionContext.
Provider scopes
| Where you provide it | Instances | Use for |
|---|---|---|
providedIn: 'root' | One, application-wide | Auth, config, most stores — the default |
providers on a route | One per activation of that route subtree | Feature state that should reset on leaving |
providers on a component | One per component instance | Per-widget state, e.g. a wizard |
providedIn: 'platform' | Shared across bootstrapped apps | Micro-frontends. Rare. |
export const routes: Routes = [
{
path: 'orders',
providers: [OrderStore], // fresh store each time the user enters
loadChildren: () => import('./features/orders/routes')
.then(m => m.ORDER_ROUTES),
},
];
Injection tokens
Interfaces disappear at compile time, so they cannot be injected. Use a token.
export interface AppConfig {
apiUrl: string;
pageSize: number;
features: { export: boolean; bulkEdit: boolean };
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG', {
providedIn: 'root',
factory: () => ({
apiUrl: '/api',
pageSize: 25,
features: { export: true, bulkEdit: false },
}),
});
// override at bootstrap
providers: [
{ provide: APP_CONFIG, useValue: loadRuntimeConfig() },
]
// consume
export class OrderApi {
private readonly config = inject(APP_CONFIG);
}
Swapping implementations
export abstract class PaymentGateway {
abstract charge(orderId: number, amount: number): Promise<PaymentResult>;
}
@Injectable()
export class StripeGateway extends PaymentGateway { /* ... */ }
@Injectable()
export class FakeGateway extends PaymentGateway {
async charge(): Promise<PaymentResult> {
return { status: 'APPROVED', reference: 'fake-1' };
}
}
providers: [
{ provide: PaymentGateway,
useClass: environment.production ? StripeGateway : FakeGateway },
]
An abstract class works as both the type and the injection token, so you avoid a separate
InjectionToken for the common case.
| Provider form | Supplies |
|---|---|
useClass | A different class for the same token |
useValue | A constant object |
useFactory | A function, with deps injected |
useExisting | An alias to another token |
multi: true | Contributes to an array — how interceptors work |
Designing services worth having
- One responsibility. An
OrderApithat only talks HTTP, and anOrderStorethat only holds state, beat oneOrderServicethat does both. - Expose signals, not raw state. Keep the writable signal private; publish
computed()selectors. - No DOM access. Services must survive server-side rendering.
- Return domain types. Map API shapes to your own interfaces at the boundary, so a backend rename touches one file.
- Do not inject a component into a service. If you need to, the dependency is backwards.
You call inject(Router) inside a click handler and get NG0203. Why?
Angular only knows which injector to use while it is constructing something. Move the
call to a field initialiser (private router = inject(Router)) — the usual
fix — or capture an Injector and wrap the later call in
runInInjectionContext.