DI is a design pattern that helps inject dependencies (services, objects) into components instead of manually creating them.
Prevents tight coupling and improves reusability.
How DI Works in Angular?
Provide the Service (in @Injectable).
Inject into Constructor (in a component or another service).
Use the Service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Provides globally
})
export class LoggerService {
log(message: string) {
console.log("Log:", message);
}
}
import { Component } from '@angular/core';
import { LoggerService } from './logger.service';
@Component({
selector: 'app-home',
template: <button (click)="logMessage()">Log</button>
})
export class HomeComponent {
constructor(private logger: LoggerService) {}
logMessage() {
this.logger.log('Hello from HomeComponent!');
}
}
Different Injection Scenarios
1️⃣ ProvidedIn: 'root' vs 'any' vs Module Level
Option Scope Usage
providedIn: 'root' Available in entire app Default
providedIn: 'any' Available in lazy-loaded modules Useful for optimizing memory
Module Level Available in specific module only providers: [MyService] in @NgModule
Top comments (0)