injectMutation
Injects a mutation: an imperative function that can be invoked which typically performs server side effects. Unlike queries, mutations are not run automatically.Signature
Parameters
A function that returns mutation options. The function is run in a reactive context using Angular’s
computed, allowing signals to be reactive.CreateMutationOptions properties:mutationFn- The function that performs the mutationonSuccess- Callback fired when the mutation succeedsonError- Callback fired when the mutation failsonSettled- Callback fired when the mutation completes (success or error)onMutate- Callback fired before the mutation function is executedthrowOnError- Whether to throw errors to the nearest error boundary- And other standard mutation options
Additional configuration for the mutation injection.
Returns
A signal-based mutation result object with the following properties and methods:Properties:
data- The data returned by the mutation functionerror- The error object if the mutation failedstatus- The status of the mutation (idle, pending, error, success)isPending- Boolean indicating if the mutation is currently executingisError- Boolean indicating if the mutation failedisSuccess- Boolean indicating if the mutation succeededisIdle- Boolean indicating if the mutation is idlevariables- The variables object passed to the mutation function
mutate(variables, options)- Function to trigger the mutation (fire-and-forget)mutateAsync(variables, options)- Function to trigger the mutation and return a promisereset()- Function to reset the mutation state
Usage
Basic example
Using mutateAsync with async/await
Optimistic updates
Reactive mutation with signals
Using with custom injector
Implementation Details
- The mutation uses Angular’s
computedsignal for reactive options - Mutations are executed outside the Angular zone for performance, then results are brought back into the zone
- Pending tasks are tracked during mutation execution for server-side rendering compatibility
- Errors can be thrown to
NgZone.onErrorifthrowOnErroris configured - The mutation observer is automatically cleaned up when the component/service is destroyed
Notes
- Must be called within an injection context (constructor, field initializer, or factory function) unless the
injectoroption is provided - Unlike queries, mutations are not executed automatically - you must call
mutateormutateAsync - The
mutatefunction is fire-and-forget and will catch errors internally - The
mutateAsyncfunction returns a promise and will throw errors if not caught - The mutation is automatically managed and cleaned up when the component/service is destroyed