Dependency Injection (DI) is a core concept in Angular that enables loose coupling and testability in applications. By injecting dependencies into components, you promote modular design and maintainability. Here's a breakdown:
Key Concepts
- Services in Angular are classes that provide functionalities (e.g., data access, utilities) to other classes via DI.
- DI in Angular works through the dependency injection module (DI module), which manages object creation and injection.
- Providers define how dependencies are created and injected, often in the
@Injectable()
decorator.
Best Practices
- Use
@Injectable()
for services that need to be injected. - Favor constructor injection for clarity and testability.
- Avoid direct instantiation of services in components.
Example Code
// Service definition
@Injectable({
providedIn: 'root'
})
export class DataService {
getData(): string {
return 'Sample data from service';
}
}
// Component using the service
constructor(private dataService: DataService) {}
ngOnInit() {
console.log(this.dataService.getData()); // Access service via DI
}
Benefits
- ✅ Reusability: Services can be shared across components.
- ✅ Maintainability: Decouples logic, making updates easier.
- ✅ Testability: Mock dependencies for unit testing.
For a deeper dive into DI in Angular, check out our Dependency Injection Tutorial. 🚀