Dependency Injection
Imagine you have a coffee shop. Instead of each barista growing their own coffee beans, making their own cups, and brewing their own coffee, you have a central supplier that delivers everything they need. This is Dependency Injection (DI) – a system that provides classes with the dependencies they need.
In Angular, DI is built-in and powerful. When a component needs a service, Angular creates or finds that service and provides it to the component – automatically.
How DI Works in Angular
1. You register a service with a provider (like `providedIn: 'root'`).
2. A component declares that it needs the service in its constructor.
3. Angular finds or creates the service and passes it to the component.
Injecting a Service into a Component
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-user',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
`
})
export class UserComponent implements OnInit {
items: string[] = [];
// Angular injects DataService here
constructor(private dataService: DataService) { }
ngOnInit() {
this.items = this.dataService.getItems();
}
}
Injecting into another Service
Services can also inject other services:
@Injectable({
providedIn: 'root'
})
export class LoggerService {
log(message: string) {
console.log(`[LOG]: ${message}`);
}
}
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private logger: LoggerService) { }
getUsers() {
this.logger.log('Fetching users...');
// fetch users logic
}
}
Provider Hierarchies
Angular has a hierarchical DI system. You can provide services at different levels:
- Root level (`providedIn: 'root'`) – One instance for the whole app.
- Module level (in @NgModule.providers) – One instance per module.
- Component level (in @Component.providers) – New instance per component.
Two Minute Drill
- Dependency Injection provides dependencies to classes automatically.
- Add dependencies in the constructor with `private` keyword.
- Angular creates and manages service instances.
- Services can inject other services.
- Provider hierarchy controls instance scope (root, module, component).
Need more clarification?
Drop us an email at career@quipoinfotech.com
