Services & RoutingCore· 35 min read

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

The CLI creates a service class
ng generate service task
# short form: ng g s task

Note: 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

A service holding the task list and its methods
// 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?

Answer: A service is a reusable class for shared data and logic, keeping components focused on the view and avoiding duplicated code.

✍️ Practice

  1. Generate a task service with ng g s task and look at the file.
  2. Add a removeTask(index) method to the service that deletes one item.

🏠 Homework

  1. Create a counter service with increment() and getValue() methods that store a shared number.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →