Dependency Injection (DI) is a design pattern where objects receive their dependencies from external sources rather than creating them. Angular has a powerful DI system built-in that makes your code more testable, maintainable, and modular.What You’ll Learn:
Creating injectable services
Understanding the injector hierarchy
Provider configurations
The modern inject() function
InjectionTokens for configuration
Multi-providers and use cases
What is Dependency Injection?
┌─────────────────────────────────────────────────────────────────────────┐│ Without DI vs With DI │├─────────────────────────────────────────────────────────────────────────┤│ ││ WITHOUT DI (Tightly Coupled) ││ ───────────────────────────── ││ class UserComponent { ││ private userService = new UserService(); // Hard to test! ││ private http = new HttpClient(); // Creates own deps ││ } ││ ││ WITH DI (Loosely Coupled) ││ ─────────────────────────── ││ class UserComponent { ││ private userService = inject(UserService); // DI provides it ││ } ││ ││ Benefits: ││ ✓ Easier to test (mock dependencies) ││ ✓ Loosely coupled code ││ ✓ Single instance (singleton) management ││ ✓ Flexible configuration ││ │└─────────────────────────────────────────────────────────────────────────┘
// users.component.tsimport { Component, inject, OnInit } from '@angular/core';import { UserService, User } from './user.service';import { AsyncPipe } from '@angular/common';@Component({ selector: 'app-users', standalone: true, imports: [AsyncPipe], template: ` @if (users$ | async; as users) { <ul> @for (user of users; track user.id) { <li>{{ user.name }} - {{ user.email }}</li> } </ul> } @else { <p>Loading...</p> } `})export class UsersComponent implements OnInit { // Modern inject() function private userService = inject(UserService); users$!: Observable<User[]>; ngOnInit() { this.users$ = this.userService.getUsers(); }}
inject() vs Constructor Injection
Angular provides two ways to inject dependencies:
Modern: inject() Function
import { Component, inject } from '@angular/core';@Component({...})export class UserComponent { // Inject in field declaration private userService = inject(UserService); private router = inject(Router); private route = inject(ActivatedRoute); // Can also inject in constructor body constructor() { const http = inject(HttpClient); // Valid here too }}
Recommendation: Use inject() for new code. It’s more concise, works with functional features like guards and resolvers, and doesn’t require decorator metadata for TypeScript.
// Application-wide singleton (recommended)@Injectable({ providedIn: 'root' })export class GlobalService {}// Platform-wide (multiple apps)@Injectable({ providedIn: 'platform' })export class PlatformService {}// No automatic provision (must provide manually)@Injectable()export class ManualService {}
Provider Configurations
Providing in Component
@Component({ selector: 'app-feature', standalone: true, providers: [ FeatureService // New instance for this component tree ], template: `...`})export class FeatureComponent { private featureService = inject(FeatureService);}
useClass - Alternative Implementation
// Interface/abstract classexport abstract class Logger { abstract log(message: string): void;}// Real implementation@Injectable()export class ConsoleLogger implements Logger { log(message: string) { console.log(`[LOG] ${message}`); }}// Mock for testing@Injectable()export class MockLogger implements Logger { log(message: string) { // Do nothing }}// Provide alternative implementation@Component({ providers: [ { provide: Logger, useClass: ConsoleLogger } ]})
useValue - Static Values
// Provide a static value@Component({ providers: [ { provide: 'API_URL', useValue: 'https://api.example.com' } ]})export class AppComponent { private apiUrl = inject<string>('API_URL');}
useFactory - Dynamic Creation
// Factory function for complex initializationexport function loggerFactory(config: AppConfig): Logger { if (config.production) { return new CloudLogger(); } return new ConsoleLogger();}@Component({ providers: [ { provide: Logger, useFactory: loggerFactory, deps: [AppConfig] // Dependencies for factory } ]})
useExisting - Alias
// Create an alias for an existing service@Component({ providers: [ NewLogger, { provide: OldLogger, useExisting: NewLogger } ]})
InjectionToken
For non-class dependencies, use InjectionToken:
// tokens.tsimport { InjectionToken } from '@angular/core';export interface AppConfig { apiUrl: string; production: boolean; features: { darkMode: boolean; analytics: boolean; };}export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');// Default value with factoryexport const API_BASE_URL = new InjectionToken<string>('api.base.url', { providedIn: 'root', factory: () => 'https://api.example.com'});
// Using the token@Component({...})export class HeaderComponent { private config = inject(APP_CONFIG); get showDarkMode() { return this.config.features.darkMode; }}