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

Signals in Services

Read-only from outside.

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

Right now, any component could call set on the items signal, and change the basket, without using the methods. Let's protect the state.

  • Anyone can call set
  • Skipping the methods
  • Protect the state

Read-only signals

Keep the writable signal private, inside the service. Share a read-only version, with as read only. Computed signals, like the count, and total, are read-only already. So outside code can read everything, but change nothing directly.

keyvalue
private list = signal(...)writable, inside only
items = list.asReadonly()read-only, shared
computed(...)read-only already
Changesonly through methods

basket.ts

The list is private, and writable. Items is a read-only view of it. Count, and total, are computed from the list. And add is still the only way in.

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

@Service()
export class Basket {
  private readonly list = signal<Book[]>([]);
  readonly items = this.list.asReadonly();
  readonly count = computed(() => this.list().length);
  readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));

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

Trying to change it

This header tries to empty the basket, with set. Run it. The build fails. Property set does not exist, on the read-only Signal type. The service is protected.

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

@Component({
  selector: 'app-header',
  template: `<button (click)="basket.items.set([])">Empty it</button>`,
})
export class Header {
  basket = inject(Basket);
}
Output
✘ [ERROR] TS2339: Property 'set' does not exist on type 'Signal<Book[]>'.

    src/app/header.ts:6:43:
      6 │ ...mplate: `<button (click)="basket.items.set([])">Empty it</button>`,
        ╵                                           ~~~
Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './books';

@Service()
export class Basket {
  private readonly list = signal<Book[]>([]);
  readonly items = this.list.asReadonly();
  readonly count = computed(() => this.list().length);
  readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));

  add(book: Book) {
    this.list.update(l => [...l, book]);
  }
}
Also uses app.ts
import { Component } from '@angular/core';
import { Header } from './header';

@Component({
  selector: 'app-root',
  imports: [Header],
  template: `<app-header />`,
})
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 },
];

Count and total

The header reads count, and total, from the service. We add Dune, and Circe, on the shelf. Run it. The header shows two books, and their total, computed in the service.

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

@Component({
  selector: 'app-header',
  template: `<h2>{{ basket.count() }} books · £{{ basket.total().toFixed(2) }}</h2>`,
})
export class Header {
  basket = inject(Basket);
}
Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './books';

@Service()
export class Basket {
  private readonly list = signal<Book[]>([]);
  readonly items = this.list.asReadonly();
  readonly count = computed(() => this.list().length);
  readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));

  add(book: Book) {
    this.list.update(l => [...l, book]);
  }
}
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 { Header } from './header';
import { Shelf } from './shelf';

@Component({
  selector: 'app-root',
  imports: [Header, Shelf],
  template: `<app-header /><app-shelf />`,
})
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(3)"}]

Summary

Keep writable signals private, share them with as read only, and add computed values. Next, providers.

Key takeaways
  • private signal
  • asReadonly()
  • computed()
Next up: Providers — where services come from