Sub topic 14
Managing Shared State in a BehaviorSubject Service
This chapter assumes you already know how Angular services and dependency injection work. It also assumes you know what a BehaviorSubject is, how the async pipe subscribes in templates, and how pipe and map derive new streams. Here you combine those pieces into one pattern: a service that owns a piece of application state and shares it with any component that needs it.
The working model
Several components often need the same data, such as a shopping cart. One component shows the item count, another lists the items, and a third adds new ones. If each component stores its own copy, the copies drift apart. A state service fixes this by holding a single copy in one place.
The pattern has three parts:
- A private
BehaviorSubjectstores the current state. It always has a value, so a new subscriber gets the latest state right away. - Public read-only observables expose that state, plus any values derived from it.
- Public methods are the only way to change the state.
Components read state through the observables and change it by calling the methods. They never push values into the subject directly.
Building the service
import { Injectable } from '@angular/core';
import { BehaviorSubject, map } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly itemsSubject = new BehaviorSubject<string[]>([]);
readonly items$ = this.itemsSubject.asObservable();
readonly count$ = this.items$.pipe(map(items => items.length));
add(item: string): void {
this.itemsSubject.next([...this.itemsSubject.value, item]);
}
}providedIn: 'root' makes the service a singleton, so every component shares the same subject. asObservable() hides the subject's next method. Callers can subscribe to items$, but they cannot emit into it. count$ is derived state. It is computed from items$, so it is never stored separately and can never fall out of sync.
The add method builds a new array with the spread operator instead of mutating the old one. Every emission therefore carries a fresh reference.
Consuming the service
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-summary',
standalone: true,
imports: [AsyncPipe],
template: `
<p>{{ count$ | async }} items</p>
<button (click)="addSample()">Add sample</button>
`,
})
export class CartSummaryComponent {
private cart = inject(CartService);
count$ = this.cart.count$;
addSample(): void {
this.cart.add('Sample item');
}
}The async pipe handles subscribing and unsubscribing for you. When any component calls add, every template bound to items$ or count$ updates.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Making the subject public | Any component can call `next` and bypass your rules | Keep it private and expose `asObservable()` |
| Mutating with `push` before `next` | Same reference is emitted, so `OnPush` components and `distinctUntilChanged` skip the change | Emit a new array or object |
| Reading `.value` in components | You get a snapshot that doesn't update later | Subscribe through the async pipe |
| Storing derived values in a second subject | The two subjects can disagree | Derive them with `map` |
| Providing the service in a component's `providers` | Each component instance gets its own state | Use `providedIn: 'root'` for app-wide state |
Exercise
Add a remove(item: string) method to CartService that removes the first matching item, and explain why it should not use splice on the current array.
Show answer
Use remove(item: string): void { const items = this.itemsSubject.value; const index = items.indexOf(item); if (index === -1) return; this.itemsSubject.next([...items.slice(0, index), ...items.slice(index + 1)]); }. splice mutates the existing array in place, so the subject would emit the same reference. OnPush components and distinctUntilChanged would treat that as no change, and any code holding the old array would see it change unexpectedly.
Exercise
A teammate exposes readonly items = this.itemsSubject; instead of asObservable(). What risk does this introduce?
Show answer
Any component can call items.next(...) and replace the cart state directly. That bypasses the service's methods and whatever rules they enforce, and it makes state changes hard to trace.