Sub topic 10
Sharing State Through Services
This chapter assumes you know how to create a service with @Injectable({ providedIn: 'root' }), how to inject it with inject(), and how component-level providers create separate instances. Some familiarity with Angular signals or RxJS BehaviorSubject helps.
The working model
A service instance is a single object. Every consumer that resolves to that instance reads and writes the same fields. That makes a service a natural home for state that several components need, such as a cart, a logged-in user, or a filter selection.
Two rules keep shared state predictable:
- The service owns writes. Consumers call methods such as
add()orclear()and never assign to the state directly. - Consumers get read-only views. With signals, that means
asReadonly()orcomputed(). With RxJS, it meansasObservable().
The injector hierarchy decides which consumers share the state. A root-provided service shares it across the whole app. A service listed in a component's providers shares it only within that component's subtree.
State with signals
Signals are the default choice for synchronous state in current Angular. Keep the writable signal private and expose read-only views of it:
import { Injectable, computed, signal } from '@angular/core';
export interface CartItem {
id: string;
name: string;
price: number;
}
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly _items = signal<CartItem[]>([]);
readonly items = this._items.asReadonly();
readonly count = computed(() => this._items().length);
readonly total = computed(() =>
this._items().reduce((sum, item) => sum + item.price, 0)
);
add(item: CartItem): void {
this._items.update(list => [...list, item]);
}
remove(id: string): void {
this._items.update(list => list.filter(item => item.id !== id));
}
clear(): void {
this._items.set([]);
}
}A component reads the values in its template. Change detection follows the signal automatically:
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-summary',
standalone: true,
template: `
<p>{{ cart.count() }} items, total {{ cart.total() }}</p>
<button (click)="cart.clear()">Clear</button>
`
})
export class CartSummaryComponent {
protected readonly cart = inject(CartService);
}State with RxJS subjects
If the state comes from streams, or your codebase already uses RxJS, a BehaviorSubject does the same job. It holds a current value and emits that value to new subscribers.
import { Injectable } from '@angular/core';
import { BehaviorSubject, map } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class FilterService {
private readonly query$ = new BehaviorSubject<string>('');
readonly query = this.query$.asObservable();
readonly hasQuery = this.query.pipe(map(q => q.length > 0));
setQuery(value: string): void {
this.query$.next(value.trim());
}
}In templates, consume the observable with the async pipe, or convert it with toSignal() from @angular/core/rxjs-interop. Both handle unsubscription for you.
Choosing between them
| Concern | Signals | BehaviorSubject |
|---|---|---|
| Reading the current value | `items()` | `subject.value`, inside the service only |
| Derived state | `computed()` | `pipe(map(...))` |
| Async events, debouncing, HTTP | Needs interop | Native operators |
| Template use | Call directly | `async` pipe or `toSignal()` |
| Subscription cleanup | Not needed | Needed unless the `async` pipe or `toSignal()` handles it |
Common errors
- Mutating in place. Writing
list.push(item); return list;insideupdate()returns the same array reference. Signals compare values withObject.is, so nothing gets notified. Always return a new array or object. - Exposing the writable source. A public
signalorBehaviorSubjectlets any component write to it, and you lose track of who changed the state. - Accidental separate instances. Adding
CartServiceto a component'sprovidersgives that subtree its own empty cart. The badge then shows 0 while the list shows items. - Manual subscriptions that never end. Calling
subscribe()in a component without cleanup leaks memory. Useasync,toSignal(), ortakeUntilDestroyed().
Exercise
A developer's CartService has add(item) { this._items.update(list => { list.push(item); return list; }); }. The badge count never changes after the first render. Why, and how do you fix it?
Show answer
push mutates the existing array and the callback returns the same reference. The signal's Object.is equality check sees no change, so it never notifies count or the template. Return a new array instead: this._items.update(list => [...list, item]);.
Exercise
CartBadgeComponent shows 0 items while ProductListComponent, which calls add(), shows the items correctly. Both inject CartService, which is providedIn: 'root'. What is the most likely cause?
Show answer
One of the components, or one of their ancestors, lists CartService in its own providers array. That creates a separate instance for that subtree, so the two components read different carts. Remove the component-level provider so both resolve to the root instance.