AI Hints
Home›Angular Tutorial›@Service and @Injectable, Sharing State in a Service and Signals in Services
Angular · Lesson 68 of 120

Sharing State in a Service

One source of truth.

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

A real basket needs whole books, not just titles. And the user must be able to remove them, too.

  • Whole books
  • Add and remove
  • One source of truth

State in a service

The service holds the state, and has a method for each change. Components never change the data directly. They call the methods, and read the signals. So every change goes through one place.

keyvalue
Serviceholds the state
Methodsadd(), remove()
Componentscall methods, read signals
Every changein one place

basket.ts

Items is now a signal of books. Add puts a book on the end of the list. Remove keeps every book, except the one with that id.

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

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

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

  remove(id: number) {
    this.items.update(list => list.filter(b => b.id !== id));
  }
}

Adding and removing

The basket view reads the items, and gives each one a remove button. The shelf, in another component, has the add buttons. We add three books, and remove The Hobbit. Run it. Two books are left. Both components worked on the same basket.

basket-view.tstypescript
import { Component, inject } from '@angular/core';
import { Basket } from './basket';

@Component({
  selector: 'app-basket-view',
  template: `
    <h3>Your basket ({{ basket.items().length }})</h3>
    @for (b of basket.items(); track b.id) {
      <p>{{ b.title }} <button (click)="basket.remove(b.id)">Remove</button></p>
    } @empty { <p>Empty</p> }
  `,
})
export class BasketView {
  basket = inject(Basket);
}
Also uses basket.ts
import { Service, signal } from '@angular/core';
import { Book } from './books';

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

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

  remove(id: number) {
    this.items.update(list => list.filter(b => b.id !== id));
  }
}
Also uses shelf.ts
import { Component, inject } from '@angular/core';
import { Basket } from './basket';
import { BOOKS } from './books';

@Component({
  selector: 'app-shelf',
  template: `
    @for (b of books.slice(0, 3); track b.id) {
      <button (click)="basket.add(b)">Add {{ b.title }}</button>
    }
  `,
})
export class Shelf {
  basket = inject(Basket);
  books = BOOKS;
}
Also uses app.ts
import { Component } from '@angular/core';
import { Shelf } from './shelf';
import { BasketView } from './basket-view';

@Component({
  selector: 'app-root',
  imports: [Shelf, BasketView],
  template: `<app-shelf /><app-basket-view />`,
})
export class App {}
Also uses books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];
Also uses actions.json
[{"click": "app-shelf button:nth-of-type(1)"}, {"click": "app-shelf button:nth-of-type(2)"}, {"click": "app-shelf button:nth-of-type(3)"}, {"click": "app-basket-view p:nth-of-type(2) button"}]

Summary

The service holds the state, and methods change it. Components only call the methods, and read the signals. Next, protecting that state.

Key takeaways
  • signal<Book[]>
  • add(), remove()
  • One source of truth
Next up: Signals in Services — read-only from outside