Sub topic 1
What dependency injection gives you in Angular
Prerequisites
Assume you know TypeScript classes and decorators, Angular components, standalone components, services, and basic route configuration.
What dependency injection gives you in Angular
Dependency injection (DI) is Angular's way to supply a class with the objects it needs. A component asks for a service instead of creating that service with new. Angular creates, stores, and supplies the service according to its provider configuration.
This separates application behavior from object construction. It also lets different parts of an application share one service or receive separate instances.
Providers and injection tokens
A provider tells Angular how to create a value for a token. A token identifies the requested dependency. A class can be its own token, while an InjectionToken is useful for strings, configuration, and other non-class values.
import { Injectable, InjectionToken } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class Logger {
log(message: string): void {
console.log(message);
}
}
export const API_URL = new InjectionToken<string>('API_URL');providedIn: 'root' registers Logger with the application's root environment injector. An explicit provider can map a token to a value, class, or existing object.
Requesting dependencies with `inject()` and constructors
Angular supports constructor injection and the inject() function. Both request a token from the current injection context.
import { Component, inject } from '@angular/core';
@Component({
selector: 'app-status',
standalone: true,
template: `<button (click)="logger.log('Ready')">Check</button>`,
})
export class StatusComponent {
protected readonly logger = inject(Logger);
constructor(private readonly constructorLogger: Logger) {}
}Use one style consistently in a class. inject() works in field initializers and functions with an injection context. Constructor parameters are familiar and work well when dependencies are part of the class's public construction contract.
Two hierarchies: environment injectors and element injectors
Angular resolves dependencies through two connected hierarchies:
Environment injectors hold broad scopes such as platform, application root, route, and legacy module scopes. Element injectors belong to components and directives. Providers declared on a component or directive normally live in its element injector.
Environment injectors: platform, root and beyond
Use the root environment injector for application-wide services, such as logging or an API client. Route providers create a scope shared by components under that route. Platform providers can be shared by multiple Angular applications on one page.
Angular starts at the requesting element's injector and searches outward through the element hierarchy. It then uses the relevant environment injector hierarchy. The first matching provider determines which instance the consumer receives.
Exercise
Where should you register a service that must be shared by the whole application?
Show answer
Register it with providedIn: 'root' or the root environment injector.