Sub topic 6
Exposing operations with withMethods
This chapter assumes you can read a store built with signalStore, withState and withComputed. It also assumes you know patchState and Angular's inject. Here you will add the part of the store that components call to change state.
What withMethods does
withMethods adds functions to the store. Components and other code call these functions, and each one decides how state changes. The state signals are read-only from outside the store, so methods are the only normal way to write to it.
The feature takes a factory function. NgRx calls the factory once per store instance and passes it the store as it exists at that point. The factory returns an object of functions.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type CartState = { items: string[] };
export const CartStore = signalStore(
{ providedIn: 'root' },
withState<CartState>({ items: [] }),
withMethods((store) => ({
addItem(name: string): void {
patchState(store, (state) => ({ items: [...state.items, name] }));
},
clear(): void {
patchState(store, { items: [] });
},
})),
);The store argument has the state signals, computed signals and methods declared before this withMethods. It is also what you pass to patchState.
Order matters
Features run top to bottom. A withMethods call can only see what appears above it. If you put it before withState, store.items does not exist and TypeScript reports an error.
You can use withMethods more than once. A second call sees the methods from the first, which is how one group of methods calls another.
Injecting dependencies
The factory runs in an injection context, so you can call inject() inside it. A default parameter is a compact way to do this.
import { Injectable, inject } from '@angular/core';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
@Injectable({ providedIn: 'root' })
export class Logger {
log(message: string): void {
console.log(message);
}
}
export const NotesStore = signalStore(
{ providedIn: 'root' },
withState({ notes: [] as string[] }),
withMethods((store, logger = inject(Logger)) => ({
add(note: string): void {
logger.log(`Adding note: ${note}`);
patchState(store, (state) => ({ notes: [...state.notes, note] }));
},
})),
);Calling inject() inside a method body fails, because methods run later, outside the injection context. Resolve dependencies in the factory and use them from the method.
Methods that call other methods
Split related methods into two withMethods calls. The second one can use the first one's results.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
export const CounterStore = signalStore(
withState({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
})),
withMethods((store) => ({
incrementTwice(): void {
store.increment();
store.increment();
},
})),
);In recent NgRx versions, members whose names start with an underscore are private. Components cannot see them, but later features in the same store can. Use this for helper methods that should not be public.
Common errors
- Mutating state. Writing
store.items().push(name)changes the array in place and does not notify signal consumers. Always build a new value and pass it topatchState. - Reusing a member name. A method named
itemswould clash with theitemsstate signal. Keep names unique across state, computed signals and methods. - Putting methods too early. A method that reads
store.total()needswithComputeddeclared above it. - Doing too much in one method. A method should describe one operation, such as
addItem. Compute derived values inwithComputedinstead of storing them from methods.
Exercise
A store has withState({ count: 0 }) and a withMethods that defines reset(). You want resetAndLog() to call reset() and then write to the console. How do you add it, and where must it go?
Show answer
Add a second withMethods after the first one. Its factory receives a store that includes reset, so resetAndLog() can call store.reset() and then log. If it were placed before the first withMethods, store.reset would not exist yet.