Open this when choosing a state pattern for a feature, writing a signal service or NgRx SignalStore, or designing injection tokens. Verified 2026-09 against https://angular.dev/guide/signals, https://angular.dev/guide/di and https://ngrx.io/guide/signals/signal-store.
1. Signal service — the default for a feature with a handful of consumers
import { Injectable, computed, inject, signal } from '@angular/core';
import { OrdersApi } from './orders-api';
import type { Order } from '../model/order';
@Injectable() // provided on the feature route, not in root
export class OrdersState {
private readonly api = inject(OrdersApi);
private readonly _orders = signal<readonly Order[]>([]);
private readonly _status = signal<'idle' | 'loading' | 'error'>('idle');
readonly orders = this._orders.asReadonly();
readonly status = this._status.asReadonly();
readonly unpaidTotal = computed(() =>
this._orders().filter((o) => !o.paid).reduce((sum, o) => sum + o.total, 0));
async load(customerId: string): Promise<void> {
this._status.set('loading');
try {
this._orders.set(await this.api.listFor(customerId));
this._status.set('idle');
} catch {
this._status.set('error');
}
}
}
Provide it on the route so it dies when the user leaves:
// orders.routes.ts
import type { Routes } from '@angular/router';
import { OrdersState } from './data/orders-state';
export default [
{ path: '', providers: [OrdersState], loadComponent: () => import('./pages/order-list').then((m) => m.OrderList) },
] satisfies Routes;
Writable signals stay private; consumers get asReadonly() and computed(). That one rule removes the whole class of "who set this?" bugs, because there is exactly one file that can write.
2. NgRx SignalStore — when the feature has entities, async methods and several consumers
import { computed, inject } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap } from 'rxjs';
import { OrdersApi } from './orders-api';
import type { Order } from '../model/order';
type OrdersSlice = { orders: readonly Order[]; loading: boolean; query: string };
export const OrdersStore = signalStore(
withState<OrdersSlice>({ orders: [], loading: false, query: '' }),
withComputed(({ orders, query }) => ({
visible: computed(() => orders().filter((o) => o.number.includes(query()))),
})),
withMethods((store, api = inject(OrdersApi)) => ({
setQuery: (query: string) => patchState(store, { query }),
load: rxMethod<string>(
pipe(
tap(() => patchState(store, { loading: true })),
switchMap((customerId) => api.listFor$(customerId)),
tap((orders) => patchState(store, { orders, loading: false })),
),
),
})),
);
signalStore,withState,withComputed,withMethods,withHooks,withProps,patchStatecome from@ngrx/signals;rxMethodfrom@ngrx/signals/rxjs-interop;withEntitiesfrom@ngrx/signals/entities.- Default to
signalStore(...)with no{ providedIn: 'root' }and list it in the route'sproviders— a root store outlives the feature and leaks state between visits and between tests. withHooks({ onInit, onDestroy })for subscriptions and initial loads;withPropsto expose a non-signal dependency;signalMethodwhen the input is a signal and you do not need RxJS.- A store never injects another feature's store. Compose in the page component, which is the only place that knows both features exist.
Reach for full NgRx Store (actions, reducers, effects, devtools time travel) only when the domain is genuinely event-sourced or several distant parts of the app react to the same event. Write the ADR; "for consistency" is not a reason.
3. The RxJS boundary
| Concern | Belongs to |
|---|---|
| A value the template renders now | signal (signal, computed, linkedSignal, toSignal) |
| A sequence over time (typeahead, WebSocket, router events, drag) | RxJS pipeline |
| One HTTP request feeding a view | httpResource() / resource() |
| A write (POST/PUT/DELETE) | HttpClient method in the API service, awaited or subscribed once |
Convert once, at the edge of the service or store: toSignal(source$, { initialValue }). Components never see an Observable; templates never contain | async on a stream created in a getter.
Operator choice, stated so reviewers can check it:
switchMap— a newer input makes the older request irrelevant (typeahead, route param change). Cancels the stale one.concatMap— order matters and nothing may be dropped (queued writes).exhaustMap— ignore new triggers while one is in flight (submit buttons, refresh).mergeMap— genuinely independent and unbounded; addtakeUntil/a concurrency limit or it becomes a request storm.
Every manual subscribe() needs takeUntilDestroyed() (from @angular/core/rxjs-interop) or an explicit Subscription torn down in inject(DestroyRef).onDestroy().
4. DI design
Injection tokens for every boundary you will want to swap: base URLs, clocks, storage, logging, feature flags.
import { InjectionToken, inject } from '@angular/core';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL', {
providedIn: 'root',
factory: () => '/api',
});
// consumer
const base = inject(API_BASE_URL);
A token with a root factory needs no provider in the happy path and is one line to override in a test or in the SSR config. That is cheaper than a class with an interface for the same job.
@Service() vs @Injectable() (v22): @Service() is a plain root singleton that uses inject() — the common case. @Injectable() stays for anything needing useClass / useValue / useFactory, a non-root scope, or constructor parameter injection. Both are correct; do not rewrite one into the other while doing unrelated work.
Functional everything at the edges: CanActivateFn, ResolveFn, HttpInterceptorFn. They are plain functions that call inject(), so they test without TestBed ceremony and compose by array order. A guard returns true, false or a UrlTree — it never calls router.navigate() itself, because an imperative navigation inside a guard races the navigation that triggered it.
Root providers live in app.config.ts only. If you find providedIn: 'root' on a service that only one feature uses, move it to the route: the bundle shrinks and the state resets on leave.