How Dependency Injection Provides Services
You ask for a service in the constructor, and Angular hands it to you automatically — that is dependency injection.
What you will learn
- Explain dependency injection in plain words
- Inject a service into a component’s constructor
- Use the injected service’s methods
Ask, and you shall receive
Dependency injection (DI) sounds scary but the idea is simple: instead of a component creating the things it needs, it just asks for them, and Angular delivers them. Your service is a “dependency”, and Angular “injects” it for you.
Tip: Analogy: at a restaurant you do not go into the kitchen to cook. You ask the waiter and the dish arrives. Angular is the waiter; the service is the dish.
Inject a service in the constructor
The constructor is a special method that runs once, automatically, the moment a component is created — a perfect place to set things up. You request a service by listing it in that constructor. Angular sees the type and passes in the shared instance.
// task-list.component.ts
import { Component } from '@angular/core';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
template: '<li *ngFor="let t of tasks">{{ t }}</li>'
})
export class TaskListComponent {
tasks: string[] = [];
constructor(private taskService: TaskService) { // ask for it
this.tasks = this.taskService.getTasks(); // use it
}
}Note: Output:
Buy milk
Walk dog
We never wrote new TaskService(). By listing it in the constructor, Angular handed us the shared service, and we called getTasks() to fill the list.
Why this is so handy
- You get the same shared instance — so data stays consistent across components.
- Components are easier to test, because you can swap in a fake service.
- You write less code — no manual wiring of objects.
Watch out: Writing new TaskService() yourself defeats the point — you would get a separate, unshared copy. Always let Angular inject it through the constructor.
Tip: The private keyword in private taskService: TaskService is a TypeScript shortcut. It both receives the service and saves it on the component as this.taskService in one line.
Q. How does a component get a service with dependency injection?
✍️ Practice
- Inject your
taskservice into a component and display its tasks with*ngFor. - Add a button that calls the service’s
addTask()and shows the updated list.
🏠 Homework
- Inject the
counterservice from the last lesson into a component and show its value, with a button to increment it.