What is dependency injection in Angular?
Asked on Sep 30, 2024
Answer
Dependency Injection (DI) in Angular is a design pattern used to manage how components and services are instantiated and connected. It allows for better code modularity and easier testing by injecting dependencies rather than hardcoding them.
<!-- BEGIN COPY / PASTE -->
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class DataService {
getData() {
return ['Data1', 'Data2', 'Data3'];
}
}
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `<ul><li *ngFor="let item of data">{{ item }}</li></ul>`,
})
export class AppComponent {
data: string[];
constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}
}
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "DataService" is marked with "@Injectable" to make it available for DI.
- The "AppComponent" uses the "DataService" by declaring it in the constructor, allowing Angular to inject the service instance.
- The "providedIn: 'root'" option makes the service a singleton, available throughout the application.
- Dependency Injection promotes loose coupling and enhances testability by allowing you to substitute mock services during testing.
Recommended Links:
← Back to All Questions