Angular Services & Dependency Injection (DI) #4
Angular Services and Dependency Injection (DI) are critical topics — and interviewers love to ask about them because they're core to Angular’s architecture.
Here’s a crisp, pen-and-paper-friendly breakdown — simple to write, easy to revise.
📦 What is a Service?
A service is a reusable class that holds logic/data you want to share across components.
Use it for:
- HTTP/API calls
- Shared state/data (e.g., cart, user info)
- Utility/helper functions
🛠️ Creating a Service
ng g service user
// user.service.ts
@Injectable({
providedIn: 'root' // makes it available app-wide
})
export class UserService {
getUser() {
return { name: 'Ankit', role: 'admin' };
}
}
🧲 What is Dependency Injection?
DI is Angular’s way of automatically giving your component the instance of a service it needs.
Think of it like this:
You don’t create objects manually using new. Angular injects them when needed.👨💻 Using a Service in a Component
// user.component.ts
export class UserComponent {
constructor(private userService: UserService) {}
ngOnInit() {
const user = this.userService.getUser();
console.log(user.name); // "Ankit"
}
}
📌 Where Can You Provide a Service?
| Location | Scope |
|---|---|
providedIn: 'root' |
Singleton — available everywhere |
providers: [] in Component |
New instance only for that component |
NgModule providers |
Shared among components of that module |
⚠️ Service Scope Interview Trick:
@Component({
selector: 'child',
providers: [CounterService]
})
Every time this component is loaded, it gets a new instance of CounterService.🧪 Real-life Example: Shared Counter
@Injectable({ providedIn: 'root' })
export class CounterService {
count = 0;
increase() { this.count++; }
}
@Component({...})
export class CompA {
constructor(public cs: CounterService) {}
}
@Component({...})
export class CompB {
constructor(public cs: CounterService) {}
}
✅ If injected with 'root', CompA and CompB share the same counter
❌ If added in providers separately, they will get different counters
🧠 Interview Questions
- What is a service in Angular?
👉 A reusable class to hold shared business logic or data - What is Dependency Injection?
👉 Angular’s design pattern to provide objects (like services) without creating them manually - When to use providedIn vs providers array?
👉 UseprovidedIn: 'root'for global services. Useproviders: []in component for isolation/testing. - How are services different from components?
👉 Components manage UI. Services handle logic/data and have no HTML.
📊 Summary Table
| Concept | Keyword/Example | Purpose |
|---|---|---|
| Service | @Injectable() |
Share logic/data across app |
| DI | constructor(private svc) |
Inject needed instance |
| providedIn | 'root' |
App-wide singleton |
| Component Provider | providers: [] |
Scoped, creates new instance |
Would you like to go deeper into:
- 🔗 HttpClient usage with services (real API calls)?
- Or 🧵 State Sharing using services with Observables?
Let me know — and keep writing those notes! 📘✍️