AI Hints
Home›Angular Tutorial›Why Services, Creating a Service and inject()
Angular · Lesson 65 of 120

Creating a Service

@Service.

⏱ 2 min read▶ Video at 1:16:51🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's create a basket service, that keeps the titles of the books the user adds.

  • A basket service
  • Keeps the titles
  • Shared

@Service

A service is a class, with the service decorator. Angular then provides it automatically, as one instance, for the whole app. The class holds the state, usually in signals, and methods that change it.

keyvalue
@Service()marks a service
Providedautomatically
One instancefor the whole app
Signals + methodsstate and changes

Generating a service

Inside the project, ng generate service, then a name, creates a service. We call it basket. The CLI creates two files, the service, and a test. Cat shows the generated class, with the service decorator.

Terminal
cd shop
ng generate service basket
CREATE src/app/basket.spec.ts (320 bytes)
CREATE src/app/basket.ts (77 bytes)
cat src/app/basket.ts
import { Service } from '@angular/core';

@Service()
export class Basket {
}

basket.ts

The service decorator makes one shared basket, for the whole app. Items is a signal, holding the book titles. Read only stops other code from replacing the signal itself. Add puts a new title in the list.

basket.tstypescript
import { Service, signal } from '@angular/core';

@Service()
export class Basket {
  readonly items = signal<string[]>([]);

  add(title: string) {
    this.items.update(list => [...list, title]);
  }
}

Summary

A service is a class with the service decorator. It keeps state in signals, and changes it with methods. Next, using it, with inject.

Key takeaways
  • @Service()
  • One instance
  • signals + methods
Next up: inject() — ask for a service