Services & DI
Dependency Injection
Angular Ka Core Pattern
💡 Dependency Injection ek restaurant waiter jaisa hai — tumhe khud kitchen jaakar khana banaने ki zaroorat nahi, tum bas "order" karo (constructor mein type declare karo), Angular khud "serve" kar deta hai (instance create karके deता hai) — tumhe "kaise banaya" jaanna zaroori nahi.
Dependency Injection (DI) ek design pattern hai — class apni DEPENDENCIES (services) khud CREATE nahi karti, unhe "INJECT" kiya jaata hai (CONSTRUCTOR ke through). Angular ka DI system automatically figure out karta hai KYA inject karna hai, aur INSTANCE provide karta hai.
@Component({
selector: 'app-user-list',
template: '<li *ngFor="let user of users">{{ user.name }}</li>'
})
export class UserListComponent {
users: any[];
// DI: Angular AUTOMATICALLY UserService ka instance provide karta hai:
constructor(private userService: UserService) {
this.users = this.userService.getUsers();
}
}
// Component ne KHUD "new UserService()" nahi likha — Angular ne diya!💉
Dependency Injection ek restaurant waiter jaisa hai — tumhe khud kitchen jaakar khana banaने ki zaroorat nahi, tum bas "order" karo (constructor mein type declare karo), Angular khud "serve" kar deta hai (instance create karके deता hai) — tumhe "kaise banaya" jaanna zaroori nahi.
1 / 2
⚡ Quick Recap
- DI = dependencies khud create nahi karte, "inject" hoti hain
- constructor(private service: ServiceType) = injection syntax
- Testability ke liye bahut important — mock services easily inject ho sakti hain
Is page mein (2 subtopics)
constructor(private serviceName: ServiceType) syntax DO cheezein ek saath karta hai — parameter declare karta hai AUR use class PROPERTY bhi bana deta hai (private/public keyword ki wajah se) — TypeScript-specific shorthand.
// Ye ek line:
constructor(private userService: UserService) { }
// Iske equivalent hai (bina shorthand ke):
// private userService: UserService;
// constructor(userService: UserService) {
// this.userService = userService;
// }Tip: private/public/protected keyword parameter ke pehle likhna TypeScript ka feature hai (Angular-specific nahi) — bahut concise hai, isliye almost HAMESHA Angular services mein ye shorthand use hota hai.
Ek component/service MULTIPLE dependencies inject kar sakta hai — bas constructor mein comma se separate karके list karo, Angular sabko automatically resolve karta hai.
export class DashboardComponent {
constructor(
private userService: UserService,
private authService: AuthService,
private logService: LoggerService
) {
this.logService.log('Dashboard loaded');
}
}Tip: Agar constructor mein BAHUT saari dependencies ho jaayein (5+), ye usually sign hai ki component/service bahut zyada responsibility le raha hai — smaller, focused pieces mein todने ka time aa gaya hai.