diff --git a/packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts b/packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts index 79d5c05cc1..ad9dc3305d 100644 --- a/packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts +++ b/packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts @@ -1,4 +1,4 @@ -import { Component, input, signal } from '@angular/core' +import { Component, Injectable, inject, input, signal } from '@angular/core' import { TestBed } from '@angular/core/testing' import { describe, expect, vi } from 'vitest' import { By } from '@angular/platform-browser' @@ -453,4 +453,45 @@ describe('injectMutation', () => { await expect(() => mutateAsync()).rejects.toThrowError(err) }) + + test('should execute callback in injection context', async () => { + const errorSpy = vi.fn() + @Injectable() + class FakeService { + updateData(name: string) { + return Promise.resolve(name) + } + } + + @Component({ + selector: 'app-fake', + template: ``, + standalone: true, + providers: [FakeService], + }) + class FakeComponent { + mutation = injectMutation(() => { + try { + const service = inject(FakeService) + return { + mutationFn: (name: string) => service.updateData(name), + } + } catch (e) { + errorSpy(e) + throw e + } + }) + } + + const fixture = TestBed.createComponent(FakeComponent) + fixture.detectChanges() + + // check if injection contexts persist in a different task + await new Promise((resolve) => queueMicrotask(() => resolve())) + + expect( + await fixture.componentInstance.mutation.mutateAsync('test'), + ).toEqual('test') + expect(errorSpy).not.toHaveBeenCalled() + }) }) diff --git a/packages/angular-query-experimental/src/inject-mutation.ts b/packages/angular-query-experimental/src/inject-mutation.ts index f7948df617..4ec2c304b9 100644 --- a/packages/angular-query-experimental/src/inject-mutation.ts +++ b/packages/angular-query-experimental/src/inject-mutation.ts @@ -70,7 +70,11 @@ export function injectMutation< } effect(() => { - observer.setOptions(optionsFn(queryClient)) + observer.setOptions( + runInInjectionContext(currentInjector, () => + optionsFn(queryClient), + ), + ) }) const result = signal(observer.getCurrentResult())