Sub topic 13
Sharing State Through Signal-Based Services
Earlier chapters kept signals inside a single component. Real applications often need the same state in several places. A cart badge in the header, a cart page, and a checkout button all care about the same items. This chapter shows how to move that state into an injectable service, called a store, that exposes signals to any component that injects it.
This chapter assumes you know Angular dependency injection and providedIn: 'root' services. It also assumes you have read the earlier chapters on signal(), computed(), and effect().
The store pattern
A signal-based store follows three rules:
- Keep the writable signal private, so only the service can change it.
- Expose a read-only view of it, plus any derived values built with
computed(). - Allow changes only through named methods such as
add()andremove().
These rules give you one place where state changes. You can then trace every change by reading the service's methods, and you don't have to search every component.
Building a cart store
import { Injectable, computed, signal } from '@angular/core';
export interface CartItem { id: string; price: number; qty: number; }
@Injectable({ providedIn: 'root' })
export class CartStore {
private readonly _items = signal<CartItem[]>([]);
readonly items = this._items.asReadonly();
readonly total = computed(() =>
this._items().reduce((sum, i) => sum + i.price * i.qty, 0)
);
add(item: CartItem) {
this._items.update(items => [...items, item]);
}
remove(id: string) {
this._items.update(items => items.filter(i => i.id !== id));
}
}asReadonly() returns a Signal<CartItem[]>. It has no set() or update() methods, so a component that injects the store can read items() but can't write to it. total is a computed signal. It recalculates only when _items changes, and only when something reads it.
Consuming the store
Any component can inject the store and read its signals in the template. Because the template reads signals, Angular knows exactly which views depend on them. This works with OnPush and zoneless change detection without extra wiring.
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { CartStore } from './cart.store';
@Component({
selector: 'app-cart-summary',
imports: [CurrencyPipe],
template: `
<p>{{ cart.items().length }} items, total {{ cart.total() | currency }}</p>
<button (click)="cart.add({ id: 'pen', price: 2.5, qty: 1 })">Add pen</button>
<button (click)="cart.remove('pen')">Remove pen</button>
`,
})
export class CartSummaryComponent {
protected readonly cart = inject(CartStore);
}Every component that injects CartStore shares the same root instance. When one component calls add(), every view that reads items() or total() updates.
Common errors
Other mistakes to watch for:
| Mistake | Effect | Fix |
|---|---|---|
| Exposing `_items` as public | Any component can call `set()` and bypass your methods | Keep it private and expose `asReadonly()` |
| Storing derived values in a second writable signal | The two signals can drift out of sync | Derive them with `computed()` |
| Providing the store in a component's `providers` by accident | Each component gets its own copy, so state isn't shared | Use `providedIn: 'root'` for app-wide state |
| Returning `this._items()` from a getter | Callers get a snapshot, not a reactive signal | Expose the signal itself |
Scoping a store to a component with providers: [CartStore] is sometimes what you want, for example one store per open editor tab. Choose that on purpose, not by accident.
Exercise
A teammate adds this method to CartStore: changeQty(id: string, qty: number) { const item = this._items().find(i => i.id === id); if (item) item.qty = qty; }. The total in the template doesn't change. Why, and how do you fix it?
Show answer
The method mutates an existing object inside the same array, so _items still holds the same reference and Object.is reports no change. total and the templates are never notified. Fix it by producing new references: this._items.update(items => items.map(i => i.id === id ? { ...i, qty } : i));
Exercise
Add a read-only count signal to CartStore that returns the total quantity of all items. Should it be a writable signal updated in add() and remove(), or something else?
Show answer
It should be a computed signal: readonly count = computed(() => this._items().reduce((n, i) => n + i.qty, 0));. A separate writable signal would have to be updated by hand in every method and could fall out of sync with _items.