Dependency Injection in Angular
From the Angular cheat sheet · Services & DI · verified Jul 2026
Dependency Injection
DI patterns and providers
typescript
// Injection token
const API_URL = new InjectionToken<string>('api.url');
// Provider configuration
providers: [
UserService,
{ provide: API_URL, useValue: 'https://api.example.com' },
{ provide: Logger, useClass: ConsoleLogger },
{ provide: Storage, useFactory: storageFactory, deps: [Window] }
]
// Inject in component
constructor(
private userService: UserService,
@Inject(API_URL) private apiUrl: string,
@Optional() private logger?: Logger
) {}💡 Use InjectionToken for non-class dependencies
⚡ providedIn: 'root' enables tree-shaking
📌 Hierarchical DI allows different instances at different levels
🔥 Use factories for complex initialization logic