Sub topic 13
Sharing State Through Signal-Based Services
Earlier chapters kept signals inside single components. Real applications need state that several components read and change: a shopping cart, the signed-in user, a set of filters. This chapter shows how to move that state into an injectable service built on signals. The service owns the data, exposes it as read-only signals, and controls every change through its methods.
This chapter assumes you know Angular dependency injection (@Injectable, inject(), providedIn) and the material from earlier chapters on signal(), computed(), and effect().
The Store Pattern
A signal-based store is a service with three parts:
- Private writable state. One or more
signal()fields that only the service can write. - Public read-only views. The same state exposed through
asReadonly(), pluscomputed()values derived from it. - Mutation methods. Named methods such as
add()orremove()that are the only way to change the state.
This gives you one source of truth. Consumers can read reactively, and they cannot corrupt the data by writing to it directly.
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));
}
}Here is what each part does:
_itemsis aWritableSignal<CartItem[]>. Because it isprivate, TypeScript stops code outside the class from callingset()orupdate()on it.asReadonly()returns aSignal<CartItem[]>that reads the same value but has noset()orupdate()methods. It is a view of the same signal, not a copy.totalis acomputed(). It recalculates only when_itemschanges and only when something reads it.add()andremove()build a new array each time. This matters, as the next section explains.
Why You Must Replace, Not Mutate
By default a signal compares the old and new values with Object.is. If you push into the existing array and then set the same array reference back, the signal sees no change. It notifies nobody, so total and every template that reads items keep showing old data.
// Wrong: same array reference, no notification
add(item: CartItem) {
this._items().push(item);
this._items.set(this._items());
}
// Right: new array reference, consumers are notified
add(item: CartItem) {
this._items.update(items => [...items, item]);
}The same rule applies to objects inside the array. To change a quantity, create a new item object and a new array:
changeQty(id: string, qty: number) {
this._items.update(items =>
items.map(i => (i.id === id ? { ...i, qty } : i))
);
}Consuming the Store in Components
Components inject the store and read its signals in their templates. Each template that reads items() or total() becomes a consumer of those signals. Angular marks the component for refresh when they change, which also works with OnPush and zoneless change detection.
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { CartStore } from './cart.store';
@Component({
selector: 'app-cart-summary',
imports: [CurrencyPipe],
template: `
<h2>Cart ({{ cart.items().length }} items)</h2>
@for (item of cart.items(); track item.id) {
<p>
{{ item.id }} x {{ item.qty }}
<button (click)="cart.remove(item.id)">Remove</button>
</p>
}
<p>Total: {{ cart.total() | currency }}</p>
`,
})
export class CartSummaryComponent {
protected readonly cart = inject(CartStore);
}import { Component, inject, input } from '@angular/core';
import { CartStore } from './cart.store';
@Component({
selector: 'app-add-button',
template: `<button (click)="addToCart()">Add to cart</button>`,
})
export class AddButtonComponent {
private readonly cart = inject(CartStore);
productId = input.required<string>();
price = input.required<number>();
addToCart() {
this.cart.add({ id: this.productId(), price: this.price(), qty: 1 });
}
}The two components never reference each other. When AddButtonComponent calls add(), CartSummaryComponent updates because both depend on the same signal.
Components can also derive their own local state from store signals:
readonly isEmpty = computed(() => this.cart.items().length === 0);Side Effects Inside a Store
A store is a good place for effects that belong to the data rather than to any one view, such as saving to storage. A service constructor is an injection context, so effect() works there. A root service lives as long as the application, so its effects do too.
import { Injectable, computed, effect, signal } from '@angular/core';
export interface CartItem { id: string; price: number; qty: number; }
const STORAGE_KEY = 'cart';
function loadItems(): CartItem[] {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? (JSON.parse(raw) as CartItem[]) : [];
} catch {
return [];
}
}
@Injectable({ providedIn: 'root' })
export class PersistentCartStore {
private readonly _items = signal<CartItem[]>(loadItems());
readonly items = this._items.asReadonly();
readonly count = computed(() =>
this._items().reduce((n, i) => n + i.qty, 0)
);
constructor() {
effect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(this._items()));
});
}
add(item: CartItem) {
this._items.update(items => {
const existing = items.find(i => i.id === item.id);
return existing
? items.map(i => (i.id === item.id ? { ...i, qty: i.qty + item.qty } : i))
: [...items, item];
});
}
clear() {
this._items.set([]);
}
}The effect reads _items(), so it runs once at startup and again after each change. If several updates happen in the same task, Angular runs the effect once with the final value.
Choosing the Provider Scope
Where you provide the store decides who shares it.
| Scope | How to declare | Lifetime | Use when |
|---|---|---|---|
| Application-wide | `@Injectable({ providedIn: 'root' })` | Whole app | Cart, current user, app settings |
| Route | `providers: [Store]` on a route config | While the route's injector exists | State for one feature area |
| Component subtree | `providers: [Store]` in `@Component` | Created and destroyed with the component | Per-widget state, such as one wizard or one editable table |
With component-level providers, each component instance gets its own store, and its children share that instance. Effects in that store are destroyed along with the component's injector, so you do not need manual cleanup.
Common Errors
Exposing the writable signal
readonly items = signal<CartItem[]>([]); // any component can call set()Any consumer can now replace the whole cart, skipping your validation. Keep the writable signal private and expose asReadonly().
Thinking `readonly` protects the signal
The readonly keyword only stops reassignment of the field. store.items.set([]) still compiles if items is a WritableSignal. Only the type returned by asReadonly() removes the write methods.
Leaking mutable inner data
asReadonly() protects the signal, not the array inside it. A consumer can still call store.items().push(x), which mutates the state without notifying anyone. For stronger guarantees, type the state as readonly CartItem[]:
private readonly _items = signal<readonly CartItem[]>([]);Then push(), splice(), and similar calls become compile errors for every consumer.
Reading signals once instead of reactively
constructor() {
const count = this.cart.items().length; // a snapshot, never updates
}A read outside a reactive context (a template, computed(), or effect()) is a plain one-time value. Read the signal where you need it, or wrap it in computed().
Putting every piece of state in one giant signal
One signal holding an object with twenty fields notifies every consumer whenever any field changes. Split state into separate signals by how often it changes and who reads it. You can still combine them with computed() where a combined view is useful.
Signals or a BehaviorSubject?
Many existing Angular services use a private BehaviorSubject with a public asObservable(). Signal stores follow the same encapsulation idea with less ceremony.
| Concern | BehaviorSubject service | Signal service |
|---|---|---|
| Read current value | `subject.value` or subscribe | `items()` |
| Derived state | `pipe(map(...))`, often `shareReplay` | `computed()`, memoized by default |
| Template usage | `async` pipe | Call the signal |
| Unsubscribe concerns | Yes, outside `async` pipe | None for reads |
| Time-based operators (debounce, retry) | Built in | Bridge with `toObservable()` |
If your store needs streams of events over time, keep the state in signals and use the RxJS interop functions from the previous chapter at the edges.
Exercise
A teammate writes toggleFavorite(id: string) { const f = this._favorites(); f.add(id); this._favorites.set(f); } where _favorites is signal<Set<string>>(new Set()). The favorites count in the header never updates. Why, and how do you fix it?
Show answer
set() receives the same Set reference, so Object.is reports no change and no consumers are notified. Create a new Set instead: this._favorites.update(f => { const next = new Set(f); next.has(id) ? next.delete(id) : next.add(id); return next; });.
Exercise
You add providers: [FilterStore] to a ProductListComponent while FilterStore also has providedIn: 'root'. Two ProductListComponent instances appear on the same page. Do they share filters, and what happens to an effect() in FilterStore's constructor when one list is destroyed?
Show answer
They do not share filters. The component-level provider gives each instance and its children its own FilterStore, which overrides the root instance for that subtree. When a list is destroyed, its injector is destroyed, and so is the effect created in that store's constructor. The other list's store and effect keep running.
Exercise
Add a discountPercent state to CartStore that only the store can write, plus a public discountedTotal that updates when either the items or the discount change. Write the new fields and the setter method.
Show answer
Add private readonly _discount = signal(0);, readonly discountPercent = this._discount.asReadonly();, and readonly discountedTotal = computed(() => this.total() * (1 - this._discount() / 100));. Add the method setDiscount(percent: number) { this._discount.set(Math.min(100, Math.max(0, percent))); }. The computed depends on both total and _discount, so it recalculates when either changes, and the setter clamps invalid values.