Sub topic 6
Exposing operations with withMethods
This chapter assumes you can write an Angular component, inject a service, and use signal and computed. It also assumes you have seen signalStore, withState and patchState from the earlier chapters. You do not need RxJS here. rxMethod comes in the next chapter.
What withMethods does
State and computed signals describe what the store holds. Methods describe what can happen to it. withMethods adds a set of functions to the store. Components call those functions, and the functions change state through patchState.
withMethods takes a factory function. NgNx calls the factory once, when the store is created. The factory receives the store as it exists so far and returns an object whose properties become methods on the store.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
export const CounterStore = signalStore(
{ providedIn: 'root' },
withState({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
reset(): void {
patchState(store, { count: 0 });
},
})),
);The store argument gives you three things:
- Every state property as a signal, such as
store.count(). - Every computed signal and method that earlier features added.
- The ability to write state through
patchState. Only code that holds the store can do this.
A component then calls store.increment(). It never touches the state directly.
Why methods form the public API
Many stores keep the state writable only from inside. In NgRx 19 and later, state is protected by default. Calling patchState(store, ...) with a store instance outside the store's own factories fails type checking. The store's constructor options include protectedState: false to turn this off. That setting is rarely a good idea, because it lets any component change any property and removes the single place where you can read and reason about every state transition.
Treat the methods as the store's public contract. A method name such as toggle or setFilter says what the user did, and the method body decides how state changes.
A fuller example
The store below injects a service, validates input, and builds one method on top of another.
import { Injectable, inject } from '@angular/core';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
@Injectable({ providedIn: 'root' })
export class IdGenerator {
private next = 1;
nextId(): number {
return this.next++;
}
}
type Note = { id: number; text: string };
type NotesState = { notes: Note[]; lastError: string | null };
const initialState: NotesState = { notes: [], lastError: null };
export const NotesStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withMethods((store, ids = inject(IdGenerator)) => ({
add(text: string): void {
const trimmed = text.trim();
if (!trimmed) {
patchState(store, { lastError: 'Text is required' });
return;
}
patchState(store, (state) => ({
notes: [...state.notes, { id: ids.nextId(), text: trimmed }],
lastError: null,
}));
},
remove(id: number): void {
patchState(store, (state) => ({
notes: state.notes.filter((note) => note.id !== id),
}));
},
})),
withMethods((store) => ({
addMany(texts: string[]): void {
texts.forEach((text) => store.add(text));
},
})),
);Three details are worth noticing.
- Dependency injection works inside the factory. The factory runs in an injection context, so you can call
inject()in its body or use a default parameter, asids = inject(IdGenerator)does above. You cannot callinject()later, inside a method body that runs after the store was created. - A second
withMethodssees the first.addManycallsstore.add, which the first block defined. Order matters: a feature can only use members declared above it. - Validation lives in the method. The
addmethod rejects empty text and records an error. Components do not need to repeat that check.
Reading current state inside a method
Inside a method you can read state in two ways. You can call the signal, as in store.notes(), or you can pass an updater function to patchState. Prefer the updater when the new value depends on the old one.
// Reads the signal, then writes. Fine, but two separate steps.
patchState(store, { count: store.count() + 1 });
// The updater receives the current state at the moment of the write.
patchState(store, (state) => ({ count: state.count + 1 }));Both work in synchronous code. The updater form is safer after an await, because a signal read taken before the await can be out of date by the time you write.
Private helpers and internal members
The factory is an ordinary function, so you can declare local helpers before the return statement. These helpers never become part of the store.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type Item = { id: number; qty: number };
export const CartStore = signalStore(
{ providedIn: 'root' },
withState<{ items: Item[] }>({ items: [] }),
withMethods((store) => {
// Not exposed on the store. Only the methods below can use it.
const withQuantity = (items: Item[], id: number, qty: number): Item[] =>
items.map((item) => (item.id === id ? { ...item, qty } : item));
return {
setQuantity(id: number, qty: number): void {
if (qty < 1) {
patchState(store, (state) => ({
items: state.items.filter((item) => item.id !== id),
}));
return;
}
patchState(store, (state) => ({ items: withQuantity(state.items, id, qty) }));
},
};
}),
);Recent NgRx versions also treat members whose names start with an underscore as private. Components cannot see them, but later features in the same store can. Check the NgRx version in your project before you rely on this.
Methods are plain closures
A store method does not use this. It closes over the store argument. That has practical effects:
- You can pass a method as a callback without binding it:
items.forEach(store.remove)and(click)="onClick(store.reset)"both work. - You can destructure a method from the store:
const { add } = store;. - You do not need arrow-function class properties to keep a stable reference.
Do not write this.store or this.notes() inside the returned object. Use the store parameter.
Async methods
A method can be async. The pattern is: set a loading flag, await the work, then write the result or the error.
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type Post = { id: number; title: string };
type PostsState = { posts: Post[]; loading: boolean; error: string | null };
export const PostsStore = signalStore(
withState<PostsState>({ posts: [], loading: false, error: null }),
withMethods((store, http = inject(HttpClient)) => ({
async load(): Promise<void> {
patchState(store, { loading: true, error: null });
try {
const posts = await firstValueFrom(http.get<Post[]>('/api/posts'));
patchState(store, { posts, loading: false });
} catch (err) {
const message = err instanceof Error ? err.message : 'Request failed';
patchState(store, { loading: false, error: message });
}
},
})),
);This is simple and readable. It also has limits:
- No cancellation. If
load()runs twice, both requests complete, and whichever finishes last wins. That may not be the one the user wants. - No reaction to signals. The method runs only when something calls it. It does not rerun when a
querysignal changes. - The caller receives a promise. Forgetting to handle it in a component leaves unhandled rejections if you do not catch inside the method.
For search boxes, polling, and anything where only the latest request matters, use rxMethod. The next chapter covers it. Keep async methods for one-shot operations such as saving a form.
Choosing where logic goes
| Concern | Put it in | Reason |
|---|---|---|
| Values stored as the source of truth | `withState` | One place for data that changes |
| Values calculated from state | `withComputed` | Cached, and cannot drift out of sync |
| Anything that writes state | `withMethods` | One public API with validation |
| Pure data shaping, such as reordering a list | A plain function outside the store | Easy to test without Angular |
Do not store a value in state if you can calculate it from other state. A visibleTodos list belongs in withComputed, not in a method that writes a second array.
Common mistakes
- Mutating state.
store.notes().push(note)changes the array in place, and signals do not notice. Always return new arrays and objects frompatchState. - Calling
inject()in the wrong place.inject()works in the factory body and in default parameters. It throws when called inside a method after the store exists. - Reusing a name. Giving a method the same name as a state property or computed signal replaces that member. Recent versions warn about this in development mode. Choose distinct names, such as a
filterstate property and asetFiltermethod. - Depending on a later feature. A
withMethodsblock cannot use members that a later block adds. Reorder the features. - Putting presentation logic in methods. A method that formats a date for display belongs in the template or a pipe.
Using the methods from a component
The component reads signals and calls methods. It does not know how the store implements either.
import { Component, inject } from '@angular/core';
import { NotesStore } from './notes.store';
@Component({
selector: 'app-notes',
template: `
<input #box (keyup.enter)="store.add(box.value); box.value = ''" />
@if (store.lastError(); as message) {
<p role="alert">{{ message }}</p>
}
<ul>
@for (note of store.notes(); track note.id) {
<li>{{ note.text }} <button (click)="store.remove(note.id)">Delete</button></li>
}
</ul>
`,
})
export class NotesComponent {
readonly store = inject(NotesStore);
}Summary
withMethods takes a factory that receives the store and returns an object of functions. Those functions are the store's public API. They call patchState, can use injected services, and can build on methods defined earlier. They are plain closures with no this. Use async methods for one-shot work, and move to rxMethod when you need cancellation or reactive inputs.
Exercise
A CartStore declares withMethods block A with addItem, then a later block B with addTwice(item) that calls store.addItem(item) two times. A teammate moves block B above block A. What happens, and why? Also, why should addItem use patchState(store, (s) => ({ items: [...s.items, item] })) rather than patchState(store, { items: [...store.items(), item] }) if it contains an await before the write?
Show answer
Block B no longer compiles, because store.addItem does not exist yet at that point. A feature can only use members declared above it, so block A must come first. For the second part, the updater form receives the state at the moment of the write. After an await, store.items() read earlier may be out of date, and writing it back would discard changes made while waiting. The updater avoids that by reading current state at write time.