Sharing Logic with a Service
A service is a plain class that holds shared data or logic, so many components can reuse it.
What you will learn
- Explain what a service is and why it helps
- Generate a service with the CLI
- Put shared data and methods in a service
Why components should not do everything
Components should mostly handle the screen. Shared work — storing a list of tasks, doing calculations, or later fetching from a server — belongs in a service. A service is just a normal TypeScript class that any component can use.
Keeping logic in a service means no copy-paste: write it once, reuse it everywhere, and update it in one place.
Generate a service
ng generate service task
# short form: ng g s taskNote: Output:
CREATE src/app/task.service.ts
You get a ready-made service class marked with @Injectable, which lets Angular share it with your components (next lesson explains how).
Put shared data and logic inside
// src/app/task.service.ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class TaskService {
private tasks = ['Buy milk', 'Walk dog'];
getTasks() {
return this.tasks;
}
addTask(title: string) {
this.tasks.push(title);
}
}Note: Output:
(No visible output yet.)
The service stores the tasks and offers getTasks() and addTask(). Any component can call these and they all share the same list — because the service exists once for the whole app.
The providedIn: ’root’ part means Angular makes one shared copy of this service for the entire app. Two different components asking for it get the exact same instance — and therefore the same data.
Tip: A good rule of thumb: if more than one component needs the same data or logic, move it into a service. Components stay small and focused on the view.
Q. What is the main purpose of a service in Angular?
✍️ Practice
- Generate a
taskservice withng g s taskand look at the file. - Add a
removeTask(index)method to the service that deletes one item.
🏠 Homework
- Create a
counterservice withincrement()andgetValue()methods that store a shared number.