Sub topic 14
Managing Shared State in a BehaviorSubject Service
Several components often need the same data. A cart badge in the header, a cart page, and a checkout button all care about the cart's contents. If each component keeps its own copy, the copies drift apart. A state service fixes this by keeping one copy of the data in one injectable class. Every component reads from that service and asks it to make changes.
This chapter assumes you already know how BehaviorSubject works, how asObservable() hides next(), how the async pipe subscribes for you, and how combineLatest merges streams. Earlier chapters covered each of these. Here you put them together into a pattern you can use in real applications.
The Shape of a State Service
A BehaviorSubject service has four parts:
- A private state subject holds the current value. Only the service can call
next()on it. - Selectors are public, read-only observables that are computed from the state.
- Update methods are public methods that compute the next state and push it into the subject.
- Effects are optional methods that do async work, such as HTTP calls, and then update the state.
Data moves in one direction. Components call methods, methods replace the state, and selectors deliver the new values back to templates.
Building a Cart Store
The service below keeps the whole cart in a single state object. The other option is one subject per field. A single object keeps related fields consistent: when an update changes items and status together, subscribers never see one field changed and the other still old.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, distinctUntilChanged, map } from 'rxjs';
export interface CartItem {
id: number;
name: string;
price: number;
quantity: number;
}
type LoadStatus = 'idle' | 'loading' | 'loaded' | 'error';
interface CartState {
items: CartItem[];
status: LoadStatus;
}
const initialState: CartState = { items: [], status: 'idle' };
@Injectable({ providedIn: 'root' })
export class CartStore {
private readonly http = inject(HttpClient);
private readonly state = new BehaviorSubject<CartState>(initialState);
// Selectors: read-only, derived, and deduplicated
readonly items$ = this.select(s => s.items);
readonly status$ = this.select(s => s.status);
readonly count$ = this.select(s =>
s.items.reduce((n, item) => n + item.quantity, 0)
);
readonly total$ = this.select(s =>
s.items.reduce((sum, item) => sum + item.price * item.quantity, 0)
);
// Update methods
add(product: Omit<CartItem, 'quantity'>): void {
const items = this.state.value.items;
const existing = items.find(i => i.id === product.id);
this.setState({
items: existing
? items.map(i =>
i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i
)
: [...items, { ...product, quantity: 1 }],
});
}
setQuantity(id: number, quantity: number): void {
const items = this.state.value.items;
this.setState({
items:
quantity <= 0
? items.filter(i => i.id !== id)
: items.map(i => (i.id === id ? { ...i, quantity } : i)),
});
}
remove(id: number): void {
this.setQuantity(id, 0);
}
clear(): void {
this.setState({ items: [] });
}
// Effect: async work that ends in a state update
load(): void {
this.setState({ status: 'loading' });
this.http.get<CartItem[]>('/api/cart').subscribe({
next: items => this.setState({ items, status: 'loaded' }),
error: () => this.setState({ status: 'error' }),
});
}
private select<T>(project: (state: CartState) => T): Observable<T> {
return this.state.pipe(map(project), distinctUntilChanged());
}
private setState(patch: Partial<CartState>): void {
this.state.next({ ...this.state.value, ...patch });
}
}Some details in this service matter more than they look:
setStateis the only place that callsnext(). Every change goes through one function. You can log it, add a breakpoint there, or later swap in a different store without touching callers.- Each update creates new objects. The methods use
map,filter, and spread syntax. They never usepushor assign to a property. This is what makesdistinctUntilChangedwork. distinctUntilChangedinselectstops a selector from emitting when its slice did not change. Changingstatusdoes not re-emititems$, because theitemsarray is still the same reference.- The subscription in
load()does not leak.HttpClientcompletes after one response, so the subscription ends by itself. If the effect used a long-lived source, you would need to tear it down.
Consuming the Store in Components
Components inject the store, read selectors through the async pipe, and call methods in event handlers. They never hold their own copy of the cart.
import { Component, inject } from '@angular/core';
import { AsyncPipe, CurrencyPipe } from '@angular/common';
import { combineLatest } from 'rxjs';
import { CartStore } from './cart.store';
@Component({
selector: 'app-cart-page',
standalone: true,
imports: [AsyncPipe, CurrencyPipe],
template: `
@if (vm$ | async; as vm) {
@if (vm.status === 'loading') {
<p>Loading cart…</p>
} @else if (vm.status === 'error') {
<p>Could not load the cart. <button (click)="cart.load()">Retry</button></p>
} @else {
@for (item of vm.items; track item.id) {
<div>
{{ item.name }} × {{ item.quantity }}
<button (click)="cart.setQuantity(item.id, item.quantity + 1)">+</button>
<button (click)="cart.setQuantity(item.id, item.quantity - 1)">−</button>
<button (click)="cart.remove(item.id)">Remove</button>
</div>
} @empty {
<p>Your cart is empty.</p>
}
<p>{{ vm.count }} items, total {{ vm.total | currency }}</p>
}
}
`,
})
export class CartPageComponent {
protected readonly cart = inject(CartStore);
readonly vm$ = combineLatest({
items: this.cart.items$,
status: this.cart.status$,
count: this.cart.count$,
total: this.cart.total$,
});
constructor() {
this.cart.load();
}
}The vm$ view model gives the template one subscription and one object to read. Every selector comes from a BehaviorSubject, so each one emits right away and combineLatest produces its first value on subscription. The template never shows a blank frame while it waits.
Choosing Where the State Lives
Where you provide the service decides who shares the state.
| Provided in | Lifetime | Shared by | Use for |
|---|---|---|---|
| `providedIn: 'root'` | Whole app | Every injector | Cart, session, user preferences |
| A route's `providers` | While the route's injector exists | Components under that route | Feature-level state, such as an admin area |
| A component's `providers` | That component instance | The component and its children | Per-widget state, such as one editable form wizard |
If you provide CartStore in a component's providers array, each instance of that component gets its own fresh cart. That is a bug when you wanted sharing and a feature when you wanted isolation. For component-scoped stores, implement ngOnDestroy in the service to call this.state.complete(). Completing the subject also completes every subscriber still listening.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Exposing the subject publicly | Any component can call `next()`, so updates come from untraceable places | Keep the subject `private`. Expose selectors and methods only |
| Mutating state (`items.push(x)` then `next(items)`) | `distinctUntilChanged` and `OnPush` components miss changes, and the UI goes stale | Always build new arrays and objects |
| Reading `.value` in components | The component shows a snapshot that never updates | Subscribe through the async pipe or `toSignal` |
| Copying state into component fields on init | Two sources of truth that drift apart | Bind the template straight to selectors |
| Business logic in components that then call `setState`-like methods | The same rule ends up written in several places | Put rules such as "quantity 0 removes the item" inside the store |
| Expensive selectors with many subscribers | The projection runs once per subscriber | Add `shareReplay({ bufferSize: 1, refCount: true })` to costly selectors |
When to Outgrow This Pattern
A BehaviorSubject store suits small to medium feature state. Watch for these signs that you need more structure:
- Many effects interact with each other, for example when cancelling one request should trigger another.
- You need undo, time-travel debugging, or a log of every action.
- Several stores update each other in chains.
At that point, a library such as NgRx Store or NgRx ComponentStore gives you the same one-way flow with dev tools and conventions for effects. A signal-based store is another option, covered in the next chapter. The mental model from this chapter carries over to all of them: private state, read-only selectors, and named update methods.
Exercise
A teammate writes addItem(item: CartItem) { const s = this.state.value; s.items.push(item); this.state.next(s); }. The cart page uses items$, which comes from the select helper. What does the user see after adding an item, and how do you fix it?
Show answer
The new item does not appear on the cart page. push mutates the existing array, so map(s => s.items) returns the same reference as before, and distinctUntilChanged suppresses the emission. The fix is to create a new array: this.setState({ items: [...this.state.value.items, item] }).
Exercise
Add a hasItems$ selector to CartStore that emits true when the cart contains at least one item. Explain why it emits less often than count$.
Show answer
Add readonly hasItems$ = this.select(s => s.items.length > 0);. The projection returns a boolean, and distinctUntilChanged only lets it through when the boolean flips. Changing quantities, or adding a second item, changes count$ but leaves hasItems$ at true, so hasItems$ does not emit.
Exercise
You provide CartStore in the providers array of both HeaderComponent and CartPageComponent. Adding an item on the cart page does not update the header badge. Why?
Show answer
Each component's providers array creates its own injector entry, so each component gets a separate CartStore instance with its own BehaviorSubject. Remove the component-level providers and rely on providedIn: 'root', so both components inject the same instance.