refactor(angular-query): require Angular v19+ and rely on component effect schedule timing #9893
main fromrefs/pull/9893/head·opened View on GitHubImproves reactivity and timing#
To benefit from the more mature signal ecosystem and PendingTasks integration in recent Angular versions this drops support for Angular v16-v18. These Angular versions are also not under LTS support anymore, so we keep support for all Angular versions currently under active or LTS support: v19 to v21
🎯 Changes#
- Bumped peer dependency from Angular 16+ to Angular 19+
- Use queueMicrotask instead of notifyManager.batchCalls to prevent render glitches fixes #9735
- Improve Angular PendingTasks integration
- Query timing now correctly depends on framework component effect scheduling
- use linkedSignal
Breaking Changes
- Requires Angular v19+
- Component effect timing may slightly change initialization order in edge cases
Aliasing query properties on a component will result in an error:
readonly #hasPreviousPage = this.query.hasPreviousPage
This should be resolved once the signalProxy is replaced.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
Release Notes#
Breaking Changes
- Angular v19+ is now required (previously v16+)
New Features
- Component effect scheduling support for Angular v19
Improvements
- Simplified query API with direct access to public query state properties
- Enhanced query lifecycle management for better component integration
- 1
Important
Review skipped#
Draft detected.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Walkthrough#
This changeset modernizes the Angular Query experimental package for Angular 19+, replacing the PendingTasks compatibility shim with Angular's native API, refactoring test suites to use standalone components with OnPush change detection, restructuring provider functions to return EnvironmentProviders, and updating core query/mutation lifecycle management to use Angular's component effect scheduling.
Changes#
Cohort / File(s) Summary Changeset & Documentation
.changeset/deep-crews-open.md,packages/angular-query-experimental/README.mdAdded changeset entry for minor release marking Angular 19+ requirement and notes about component effect scheduling. Updated README to reflect Angular 19+ minimum version requirement. Package Configuration
packages/angular-query-experimental/package.jsonUpdated peer dependency constraints for @angular/commonand@angular/corefrom >=16.0.0 to >=19.0.0.Example Components
examples/angular/infinite-query-with-max-pages/src/app/components/example.component.tsReplaced private wrapper methods with direct public query methods (hasNextPage, isFetchingNextPage, hasPreviousPage, isFetchingPreviousPage). Removed private method declarations. Example Templates
examples/angular/optimistic-updates/src/app/components/optimistic-updates.component.tsChanged ngFor tracking from "task" item to "$index" for template loop optimization. Core Query Logic
packages/angular-query-experimental/src/create-base-query.tsMajor refactor of observer lifecycle management: introduced dedicated observer tracking, result signal composition via linkedSignal, explicit pending tasks lifecycle via PendingTasks and DestroyRef, batch updates through notifyManager and NgZone, and error handling for fatal errors. Core Mutation Logic
packages/angular-query-experimental/src/inject-mutation.tsReplaced custom PENDING_TASKS token with Angular's native PendingTasks API. Renamed pending task tracking variable from pendingTaskRef to taskCleanupRef to store cleanup function from PendingTasks.add(). Compatibility Removal
packages/angular-query-experimental/src/pending-tasks-compat.tsRemoved entire compatibility shim file including PENDING_TASKS injection token, PendingTasksCompat type, and fallback factory (no longer needed with Angular 19+). Provider Architecture
packages/angular-query-experimental/src/providers.tsUpdated provideTanStackQuery and provideAngularQuery to return EnvironmentProviders instead of Provider arrays via makeEnvironmentProviders. Expanded QueryFeature ɵproviders type to accept Provider | EnvironmentProviders. Devtools Integration
packages/angular-query-experimental/src/devtools/with-devtools.tsReplaced ENVIRONMENT_INITIALIZER factory pattern with provideEnvironmentInitializer wrapping. Introduced explicit destroyDevtools helper and lazy initialization of TanstackQueryDevtools via async import. Maintains error handling for missing devtools installation. Test Suite: Infinite Query
packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.tsReplaced TestBed.runInInjectionContext with standalone component approach. Created temporary standalone components with OnPush change detection to host injectInfiniteQuery calls. Updated test flow to create fixture and extract query from componentInstance. Test Suite: Mutation State
packages/angular-query-experimental/src/__tests__/inject-mutation-state.test.tsAdded ChangeDetectionStrategy import and set OnPush change detection on FakeComponent decorator. Test Suite: Mutation
packages/angular-query-experimental/src/__tests__/inject-mutation.test.tsAdded ChangeDetectionStrategy import and configured OnPush change detection in two @Componentdecorators for test components.Test Suite: Queries
packages/angular-query-experimental/src/__tests__/inject-queries.test.tsAdded ChangeDetectionStrategy import and applied OnPush change detection to Page component decorator. Test Suite: Query (Extensive)
packages/angular-query-experimental/src/__tests__/inject-query.test.tsComprehensive refactor from direct injection context to component-based testing. Created standalone test components with OnPush change detection for each test scenario. Updated test setup to use TestBed.createComponent and fixture.detectChanges(). Preserved all type inferences and assertions on signals (data(), error(), status()). Expanded coverage with advanced scenarios: dependent queries, dynamic keys via signals, throwOnError handling, staleTime, refetch, enabled toggling, and HttpClient integration. Test Suite: Pending Tasks
packages/angular-query-experimental/src/__tests__/pending-tasks.test.tsRefactored multiple test cases to wrap query injections in standalone components with OnPush change detection. Replaced TestBed.runInInjectionContext blocks with fixture-based component instantiation. Updated assertions to reference fixture.componentInstance. Adjusted lifecycle interactions with explicit fixture.detectChanges() calls. Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
packages/angular-query-experimental/src/create-base-query.ts: Major refactor of observer lifecycle with new signal composition patterns, pending tasks integration, and error handling—requires careful verification that all observer state transitions work correctly and that synchronous updates are now properly handled.packages/angular-query-experimental/src/__tests__/inject-query.test.ts: Extensive test refactoring with numerous test cases migrated to component-based approach; requires verification that all type inferences, assertions, and behavioral scenarios are correctly preserved.packages/angular-query-experimental/src/providers.ts: API signature changes (Provider arrays → EnvironmentProviders); review impacts on all consumers and verify composition logic with makeEnvironmentProviders.packages/angular-query-experimental/src/devtools/with-devtools.ts: Control-flow restructuring from factory to provideEnvironmentInitializer pattern; verify initialization and teardown behavior.- Multiple test files: Consistent OnPush change detection additions across test suite require cross-verification that the pattern is correctly applied and doesn't introduce change detection issues.
Possibly related PRs#
- #9666: Directly related—both modify Angular 19+ PendingTasks integration, update create-base-query and inject-mutation to use native PendingTasks, and refactor pending-tasks compatibility layer.
- #9270: Directly related—both refactor Angular devtools integration, restructure with-devtools.ts to use new initialization patterns, and update provider architecture.
- #9615: Related—both modify the Angular mutation injection code path (inject-mutation.ts) and update PendingTasks usage.
Poem#
🐰 A rabbit's tale of Angular grace, Where pending tasks find their place, No more compat shims to hide— Version nineteen, our trusted guide! Synchronous updates, smooth and fast, This refactor was worth the task! ✨
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title 'Refactor/require angular v19' is directly related to the main objective of the PR, which requires Angular v19+ by bumping peer dependencies and refactoring internal code. Description check ✅ Passed The PR description follows the template structure with a 'Changes' section detailing modifications, breaking changes, and notes about limitations, plus a completed Release Impact checkbox indicating a changeset was generated. Linked Issues check ✅ Passed The PR addresses the synchronous optimistic updates issue (#9735) by replacing notifyManager.batchCalls with queueMicrotask and improving Angular PendingTasks integration to ensure query timing depends on component effect scheduling. Out of Scope Changes check ✅ Passed All changes are scoped to the Angular v19+ migration: peer dependency updates, refactoring for PendingTasks integration, use of linkedSignal, and test updates to reflect Angular component-based patterns.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands and usage tips.github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: angular-query-experimental
View your CI Pipeline Execution ↗ for commit 75cb8ca643d5119b510002f36fddd414e1f0f81e
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 2m 21s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 9s View ↗
☁️ Nx Cloud last updated this comment at
2025-11-23 17:02:21UTC@coderabbitai review
✅ Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
More templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-chat
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-eslint-legacy
- @tanstack/query-example-react-infinite-query-with-max-pages
- @tanstack/query-example-react-load-more-infinite-scroll
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-nextjs-suspense-streaming
- @tanstack/query-example-react-offline
- @tanstack/query-example-react-optimistic-updates-cache
- @tanstack/query-example-react-optimistic-updates-ui
- @tanstack/query-example-react-pagination
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-router
- @tanstack/query-example-react-rick-morty
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars
- @tanstack/query-example-react-suspense
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-start-streaming
- @tanstack/query-example-svelte-auto-refetching
- @tanstack/query-example-svelte-basic
- @tanstack/query-example-svelte-load-more-infinite-scroll
- @tanstack/query-example-svelte-optimistic-updates
- @tanstack/query-example-svelte-playground
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr
- @tanstack/query-example-svelte-star-wars
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-nuxt3
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-simple
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9893@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9893@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9893@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9893@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@9893@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@9893@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9893@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9893@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@9893@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@9893@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9893@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9893@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@9893@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9893@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9893@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@9893@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9893@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9893@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@9893@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9893commit:
75cb8caCodecov Report#
:x: Patch coverage is
94.89051%with7 linesin your changes missing coverage. Please review. :white_check_mark: Project coverage is 94.48%. Comparing base (66a194e) to head (75cb8ca). :warning: Report is 23 commits behind head on main.Additional details and impacted files
@@ Coverage Diff @@ ## main #9893 +/- ## =========================================== + Coverage 45.78% 94.48% +48.69% =========================================== Files 200 20 -180 Lines 8413 435 -7978 Branches 1922 99 -1823 =========================================== - Hits 3852 411 -3441 + Misses 4113 23 -4090 + Partials 448 1 -447Components Coverage Δ @tanstack/angular-query-experimental 94.23% <94.89%> (+0.37%):arrow_up: @tanstack/eslint-plugin-query ∅ <ø> (∅)@tanstack/query-async-storage-persister ∅ <ø> (∅)@tanstack/query-broadcast-client-experimental ∅ <ø> (∅)@tanstack/query-codemods ∅ <ø> (∅)@tanstack/query-core ∅ <ø> (∅)@tanstack/query-devtools ∅ <ø> (∅)@tanstack/query-persist-client-core ∅ <ø> (∅)@tanstack/query-sync-storage-persister ∅ <ø> (∅)@tanstack/query-test-utils ∅ <ø> (∅)@tanstack/react-query ∅ <ø> (∅)@tanstack/react-query-devtools ∅ <ø> (∅)@tanstack/react-query-next-experimental ∅ <ø> (∅)@tanstack/react-query-persist-client ∅ <ø> (∅)@tanstack/solid-query ∅ <ø> (∅)@tanstack/solid-query-devtools ∅ <ø> (∅)@tanstack/solid-query-persist-client ∅ <ø> (∅)@tanstack/svelte-query ∅ <ø> (∅)@tanstack/svelte-query-devtools ∅ <ø> (∅)@tanstack/svelte-query-persist-client ∅ <ø> (∅)@tanstack/vue-query ∅ <ø> (∅)@tanstack/vue-query-devtools ∅ <ø> (∅):rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
arnoud-dv(GitHub profile, opens in a new tab) changed the title
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/angular-query-experimental/src/__tests__/inject-query.test.ts (1)
712-983: Add direct-call test variant to properly exercise "outside injection context" behaviorThe current test at line 712 instantiates a component inside TestBed, which provides an injection context. This means
injectQueryis called within an existing injection context, not outside it—unlike the pattern used consistently acrossinjectMutation,injectIsFetching,injectIsMutating, andinjectMutationStatetests.To match the established pattern and properly verify that passing
{ injector }allows usage outside an injection context, add a direct-call variant alongside the component-based test:const injector = TestBed.inject(Injector) expect(() => injectQuery( () => ({ queryKey: ['manualInjector'], queryFn: () => sleep(0).then(() => 'Some data'), }), { injector }, ), ).not.toThrow()The new PendingTasks-oriented tests (
whenStable(), synchronousqueryFn,staleTime, enabled transitions, and invalidation) are correctly implemented per Angular 20 testing guidance.🧹 Nitpick comments (6)
examples/angular/optimistic-updates/src/app/components/optimistic-updates.component.ts (1)
39-41: Tracking by$indexis acceptable for this demoUsing
track $indexis fine here since the list is effectively append-only and tasks are simple values. Be aware this will remount items on reordering; if you ever introduce reordering or stable ids, consider tracking by a unique task identifier instead.packages/angular-query-experimental/src/providers.ts (1)
1-9: Consider flattening feature providers before callingmakeEnvironmentProvidersprovideTanStackQuerynow returnsEnvironmentProviders, which is good. However, the current call:return makeEnvironmentProviders([ provideQueryClient(queryClient), features.map((feature) => feature.ɵproviders), ])builds a nested structure (
Provider | Array<Provider | EnvironmentProviders>). While Angular DI usually flattens provider arrays at runtime, this shape is a bit awkward for TypeScript and diverges from common patterns.To align more closely with Angular’s own helpers and keep types clean, consider flattening:
export function provideTanStackQuery( queryClient: QueryClient | InjectionToken<QueryClient>, ...features: Array<QueryFeatures>, ): EnvironmentProviders { const featureProviders = features.flatMap((feature) => feature.ɵproviders) return makeEnvironmentProviders([ provideQueryClient(queryClient), ...featureProviders, ]) }This also fits well with the widened
ɵproviders: Array<Provider | EnvironmentProviders>and keepsQueryFeaturecomposition straightforward.Please verify this against the current
makeEnvironmentProviderssignature and Angular’s own helper implementations (e.g.provideRouter,provideHttpClient) to ensure consistent usage.Also applies to: 110-118, 129-132, 142-145, 153-156
packages/angular-query-experimental/src/devtools/with-devtools.ts (1)
11-12: Devtools env-initializer and lifecycle management look solid; refine missing-client error pathThe move to
provideEnvironmentInitializerwith a signal-driveneffectis well-structured:- Browser-only guard and
DEVTOOLS_PROVIDEDflag prevent duplicate initialization. shouldLoadToolsSignal+ effect correctly handle “load, update, destroy” behavior as options change.- Dynamic import is safely guarded by
injectorIsDestroyed, and devtools teardown is wired intoDestroyRef.
One small nit:
getResolvedQueryClient()throws'No QueryClient found', but that error is funneled into the same.catchblock that logs:'Install @tanstack/query-devtools or reinstall without --omit=optional.'This message is misleading when the real issue is a missing
QueryClientrather than a missing devtools package.Consider branching in the
catchto distinguish these cases, e.g.:.catch((error: unknown) => { if (error instanceof Error && error.message === 'No QueryClient found') { console.error( 'Angular Query Devtools: No QueryClient was found. ' + 'Provide one via provideTanStackQuery or via devtools options.', error, ) return } console.error( 'Install @tanstack/query-devtools or reinstall without --omit=optional.', error, ) })This will make configuration issues much easier to diagnose.
Please confirm this behavior against your intended public docs for
withDevtoolsso the error messaging matches how you expect users to wire up theirQueryClient.Also applies to: 13-14, 61-71, 72-112, 113-169
packages/angular-query-experimental/src/create-base-query.ts (1)
2-10: Observer lifecycle, PendingTasks, and microtask batching are wired correctly; tiny naming nitThis refactor in
createBaseQuerylooks well thought out:PendingTasksintegration viastartPendingTask/stopPendingTaskties task lifetime tofetchStatusand ensures cleanup on both subscription teardown andDestroyRef.onDestroy.queueMicrotaskaroundnotifyManager.batchplusngZone.runshould align query notifications with Angular’s component effect scheduling and avoid the optimistic-update flicker you were seeing.linkedSignalkeyed bydefaultedOptionsSignal, together withtrackObserverResult/autoTrackResultProperties, maintainsnotifyOnChangePropssemantics while still allowing optimistic results.OBSERVER_NOT_READY_ERRORis a good defensive guard against reading query state during construction; it will surface misuses clearly.
Only minor nit: the error message
'injectQuery: QueryObserver not initialized yet. Avoid reading the query result during construction'is slightly misleading when
createBaseQuerybacks bothinjectQueryandinjectInfiniteQuery. If you ever touch this again, consider a more generic wording (e.g. “Angular Query injection: …”) to avoid confusion in stack traces.Overall, the lifecycle and batching changes look consistent with the PR objectives.
Given the subtle timing behavior this is meant to fix, please re-run the original optimistic-update repro (issue #9735) and any SSR/restoration scenarios you have to confirm the microtask-based batching behaves as intended across Angular 19–21.
Also applies to: 48-75, 91-147, 148-185, 186-215, 216-217
packages/angular-query-experimental/src/__tests__/inject-query.test.ts (2)
345-520: Reactive options tests look good; consider explicitdetectChanges()after enablingThe signal-driven tests (
options contained signal change,enabledsignal, dependent queries, and dynamicqueryKeyforrefetch) are nicely migrated to component-scoped queries and make good use of external signals + class fields to verify that options are recomputed under Angular signals.One small robustness tweak: in
test('should only run query once enabled signal is set to true'), the query’senabledoption depends onthis.enabled()but afterenabled.set(true)there is no explicitfixture.detectChanges(). While this likely works today becauseinjectQuerytracks signals directly, adding a change detection call would make the test less coupled to internal implementation details:@@ - enabled.set(true) - - await vi.advanceTimersByTimeAsync(11) + enabled.set(true) + fixture.detectChanges() + + await vi.advanceTimersByTimeAsync(11)This keeps behavior the same while making the dependency on Angular’s re-evaluation semantics explicit. Based on learnings.
522-645:throwOnErrortests are thorough; watch globalprocesshandler usageThe updated
throwOnErrortests now:- Verify callback-based
throwOnErrorusing an OnPush component. - For the “throws” variants, hook both
NgZone.onErrorandprocess.on('uncaughtException')and assert they receive the expected error, cleaning up theprocesslistener in both the handler andfinallyblock.
This gives strong coverage of how errors escape into Angular and Node. The only caveat is that relying on
process.on('uncaughtException')is globally scoped; if other tests ever emit uncaught exceptions while these promises are pending, it could cause cross-test interference. If that becomes an issue, you might want to gate these tests behind a dedicated runner or add some defensive checks in the handler to ensure the error matches the expected shape/message before resolving.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ae47807851064567cf1f9604d4c84f9ee3891c36 and d71c4e3732e491afae64a888cbb85eecf9916b8c.
📒 Files selected for processing (16)
.changeset/deep-crews-open.md(1 hunks)examples/angular/infinite-query-with-max-pages/src/app/components/example.component.ts(1 hunks)examples/angular/optimistic-updates/src/app/components/optimistic-updates.component.ts(1 hunks)packages/angular-query-experimental/README.md(1 hunks)packages/angular-query-experimental/package.json(1 hunks)packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.ts(3 hunks)packages/angular-query-experimental/src/__tests__/inject-mutation-state.test.ts(2 hunks)packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts(3 hunks)packages/angular-query-experimental/src/__tests__/inject-queries.test.ts(2 hunks)packages/angular-query-experimental/src/__tests__/inject-query.test.ts(20 hunks)packages/angular-query-experimental/src/__tests__/pending-tasks.test.ts(8 hunks)packages/angular-query-experimental/src/create-base-query.ts(4 hunks)packages/angular-query-experimental/src/devtools/with-devtools.ts(2 hunks)packages/angular-query-experimental/src/inject-mutation.ts(4 hunks)packages/angular-query-experimental/src/pending-tasks-compat.ts(0 hunks)packages/angular-query-experimental/src/providers.ts(5 hunks)
💤 Files with no reviewable changes (1)
- packages/angular-query-experimental/src/pending-tasks-compat.ts
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: sukvvon Repo: TanStack/query PR: 9892 File: packages/solid-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx:331-335 Timestamp: 2025-11-22T09:06:05.219Z Learning: In TanStack/query test files, when a queryFn contains side effects (e.g., setting flags for test verification), prefer async/await syntax for clarity; when there are no side effects, prefer the .then() pattern for conciseness.Learnt from: arnoud-dv Repo: TanStack/query PR: 9669 File: docs/framework/angular/guides/testing.md:49-56 Timestamp: 2025-09-21T00:31:02.518Z Learning: TestBed.tick() is a valid API introduced in Angular 20 for triggering effects in unit tests, similar to ApplicationRef.tick() but for testing contexts.📚 Learning: 2025-09-02T17:57:33.184Z
Learnt from: TkDodo Repo: TanStack/query PR: 9612 File: packages/query-async-storage-persister/src/asyncThrottle.ts:0-0 Timestamp: 2025-09-02T17:57:33.184Z Learning: When importing from tanstack/query-core in other TanStack Query packages like query-async-storage-persister, a workspace dependency "tanstack/query-core": "workspace:*" needs to be added to the package.json.Applied to files:
packages/angular-query-experimental/package.jsonpackages/angular-query-experimental/src/inject-mutation.tspackages/angular-query-experimental/src/create-base-query.tspackages/angular-query-experimental/src/providers.ts
📚 Learning: 2025-11-22T09:06:05.219Z
Learnt from: sukvvon Repo: TanStack/query PR: 9892 File: packages/solid-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx:331-335 Timestamp: 2025-11-22T09:06:05.219Z Learning: In TanStack/query test files, when a queryFn contains side effects (e.g., setting flags for test verification), prefer async/await syntax for clarity; when there are no side effects, prefer the .then() pattern for conciseness.Applied to files:
.changeset/deep-crews-open.mdpackages/angular-query-experimental/src/inject-mutation.tspackages/angular-query-experimental/src/__tests__/inject-infinite-query.test.tspackages/angular-query-experimental/src/__tests__/inject-query.test.tspackages/angular-query-experimental/src/__tests__/pending-tasks.test.tspackages/angular-query-experimental/src/create-base-query.ts
📚 Learning: 2025-09-21T00:31:02.518Z
Learnt from: arnoud-dv Repo: TanStack/query PR: 9669 File: docs/framework/angular/guides/testing.md:49-56 Timestamp: 2025-09-21T00:31:02.518Z Learning: TestBed.tick() is a valid API introduced in Angular 20 for triggering effects in unit tests, similar to ApplicationRef.tick() but for testing contexts.Applied to files:
.changeset/deep-crews-open.mdpackages/angular-query-experimental/src/__tests__/inject-queries.test.tspackages/angular-query-experimental/src/__tests__/inject-infinite-query.test.tspackages/angular-query-experimental/src/__tests__/inject-query.test.tspackages/angular-query-experimental/src/__tests__/pending-tasks.test.ts
📚 Learning: 2025-08-19T03:18:18.303Z
Learnt from: oscartbeaumont Repo: TanStack/query PR: 9564 File: packages/solid-query-devtools/src/production.tsx:2-3 Timestamp: 2025-08-19T03:18:18.303Z Learning: In the solid-query-devtools package, the codebase uses a pattern of type-only default imports combined with typeof for component type annotations (e.g., `import type SolidQueryDevtoolsComp from './devtools'` followed by `typeof SolidQueryDevtoolsComp`). This pattern is consistently used across index.tsx and production.tsx files, and the maintainers prefer consistency over changing this approach.Applied to files:
packages/angular-query-experimental/src/devtools/with-devtools.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Test
🔇 Additional comments (15)
packages/angular-query-experimental/README.md (1)
32-32: Clear and well-placed version requirement notice.The Quick Start update effectively communicates the Angular 19+ requirement before installation steps, preventing compatibility issues upfront.
.changeset/deep-crews-open.md (1)
1-5: Well-structured changeset entry.The format and content are correct: minor version bump with a clear summary linking the version requirement to the underlying architectural change (component effect scheduling).
packages/angular-query-experimental/package.json (1)
108-109: Peer dependency constraints are correct and well-scoped.The constraints (
>=19.0.0) properly enforce the Angular 19+ requirement while allowing compatible future versions. DevDependencies at^20.0.0provide a reasonable development environment aligned with the peer constraint.packages/angular-query-experimental/src/inject-mutation.ts (1)
4-11: PendingTasks integration and cleanup look correctThe switch to Angular’s
PendingTasksplustaskCleanupRefworks as expected: you add once whenstate.isPendingbecomes true, clear on resolution, and also clean up on effect teardown. This keeps the pending-task count accurate and avoids leaks even if the effect re-runs or unsubscribes while pending.Please double-check against the Angular 19+/20
PendingTasks.add()contract (return type and availability) for all supported targets, just to be sure there are no surprising platform differences.Also applies to: 61-63, 128-144, 161-164
packages/angular-query-experimental/src/__tests__/inject-mutation-state.test.ts (1)
2-8: OnPush change detection onFakeComponentlooks correctUsing
ChangeDetectionStrategy.OnPushonFakeComponentwhile driving it viasetFixtureSignalInputsand explicitfixture.detectChanges()keeps the test closer to real-world usage without changing its assertions. No issues spotted.Also applies to: 142-181
packages/angular-query-experimental/src/__tests__/inject-mutation.test.ts (1)
3-9: OnPush for mutation input tests is consistent and safeThe added
ChangeDetectionStrategy.OnPushon the fake components used in the required-signal-input tests fits the new testing pattern (standalone + OnPush + explicitdetectChanges()) and doesn't change the mutation semantics. Looks good.Also applies to: 305-341
packages/angular-query-experimental/src/__tests__/inject-queries.test.ts (1)
4-8: OnPush onPagecomponent keeps the test aligned with production usageSwitching the test
Pagecomponent toChangeDetectionStrategy.OnPushwhile still rendering it via@testing-library/angularmaintains the intended behavior of theinjectQuerieseffect-driven snapshot while aligning with the library's recommended pattern.Also applies to: 32-42
packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.ts (1)
31-78: Component-scoped infinite query test matches the new Angular integrationRefactoring the infinite-query test to a standalone, OnPush
TestComponentwhosequeryfield usesinjectInfiniteQueryand is accessed via a fixture keeps the assertions identical while better exercising the real integration (component effects, PendingTasks, fake timers). This pattern looks solid.packages/angular-query-experimental/src/__tests__/pending-tasks.test.ts (5)
55-89: Synchronous queryFn +whenStable()test correctly exercises PendingTasksWrapping the synchronous
queryFnin a standalone, OnPush component and assertingstatus: 'pending'beforeapp.whenStable()then'success'afterward ensures the PendingTasks integration still treats synchronous resolutions as async from Angular’s perspective. The flow and timer usage look sound.
195-231: Rapid refetch test nicely validates PendingTasks with side-effectful queryFnThe new
TestComponentwithcallCountand anasyncqueryFn(incrementingcallCountthen awaitingsleep) is a good fit for validating that multiple rapidrefetch()calls do not leak PendingTasks. Usingawait vi.advanceTimersByTimeAsync(20)plusapp.whenStable()should flush all attempts deterministically. This aligns with the async/await style for side-effectful queryFns. Based on learnings.
233-279: Offline-start test robustly covers paused queries and PendingTasks blockingThe new
"start-offline"test that:- sets
onlineManageroffline, - initializes an
injectQuerywithnetworkMode: 'online', - verifies
status: 'pending'+fetchStatus: 'paused', and - checks that
app.whenStable()does not resolve until the app comes back online
is a good regression test for PendingTasks behavior when queries never enter the
fetchingstate. The microtask and timer sequencing looks appropriate.
348-403: Component destruction tests correctly combine OnPush and PendingTasks cleanupAdding
ChangeDetectionStrategy.OnPushtoTestComponentand callingfixture.detectChanges()before starting the query/mutation ensures the operations are actually in-flight when the component is destroyed. The subsequentapp.whenStable()expectations validate that PendingTasks entries are cleaned up even if queries/mutations are torn down mid-flight. This is a solid coverage improvement.
406-459: Concurrent queries component test aligns well with new effect schedulingThe new standalone, OnPush
TestComponenthosting three concurrent queries (two async, one synchronous) and driving them through a fixture gives good coverage of concurrent PendingTasks behavior in a realistic component context. The expectations before and afterapp.whenStable()look correct and should catch regressions in scheduling or task cleanup.packages/angular-query-experimental/src/__tests__/inject-query.test.ts (2)
52-260: Type inference test via standalone OnPush component looks correctMoving the “should return the correct types” assertions into a standalone, OnPush
TestComponentthat hosts a variety ofinjectQueryusages keeps theexpectTypeOfchecks intact while aligning with the rest of the test suite’s component-based setup. Although a few queryFns (e.g. thefetch('return Promise<any')case) will run at runtime, they don’t influence the compile-time type assertions and mirror the previous behavior.
262-343: Basic pending/success/error signal tests are well-adapted to the component patternThe refactored tests for:
- initial pending state,
- successful resolution, and
- rejection with appropriate error state
now use standalone, OnPush components with
queryas a field plus fixture-drivendetectChanges(). The timer usage and assertions onstatus,data, and the variousis*helpers correctly exercise the adapter’s behavior under the new effect scheduling.@@ -38,16 +37,17 @@37+ this.query.isFetchingNextPage()3838 ? 'Loading more...'39- : this.#hasNextPage()39+ : this.query.hasNextPage()4040 ? 'Load newer'4141 : 'Nothing more to load',4242 )43434444 readonly previousButtonDisabled = computed(45- () => !this.#hasPreviousPage() || this.#isFetchingNextPage(),45+ () => !this.query.hasPreviousPage() || this.query.isFetchingNextPage(),4646 )4747 readonly previousButtonText = computed(() =>48- this.#isFetchingPreviousPage()48+ this.query.isFetchingPreviousPage()4949 ? 'Loading more...'50- : this.#hasPreviousPage()50+ : this.query.hasPreviousPage()5151 ? 'Load Older'5252 : 'Nothing more to load',5353 )⚠️ Potential issue | 🟠 Major
Fix
previousButtonDisabledto useisFetchingPreviousPage()previousButtonDisabledcurrently checksthis.query.isFetchingNextPage(), while the text and behavior for the previous button useisFetchingPreviousPage(). This likely means the "Previous" button can remain enabled while a previous-page fetch is in-flight, or be disabled for an unrelated next-page fetch.Consider aligning the disabled logic with the previous-page fetch state:
- readonly previousButtonDisabled = computed( - () => !this.query.hasPreviousPage() || this.query.isFetchingNextPage(), - ) + readonly previousButtonDisabled = computed( + () => !this.query.hasPreviousPage() || this.query.isFetchingPreviousPage(), + )📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
readonly nextButtonDisabled = computed( () => !this.query.hasNextPage() || this.query.isFetchingNextPage(), ) readonly nextButtonText = computed(() => this.query.isFetchingNextPage() ? 'Loading more...' : this.query.hasNextPage() ? 'Load newer' : 'Nothing more to load', ) readonly previousButtonDisabled = computed( () => !this.query.hasPreviousPage() || this.query.isFetchingPreviousPage(), ) readonly previousButtonText = computed(() => this.query.isFetchingPreviousPage() ? 'Loading more...' : this.query.hasPreviousPage() ? 'Load Older' : 'Nothing more to load', )🤖 Prompt for AI Agents
In examples/angular/infinite-query-with-max-pages/src/app/components/example.component.ts around lines 32 to 53, the previousButtonDisabled computed currently checks this.query.isFetchingNextPage() instead of using this.query.isFetchingPreviousPage(), causing the Previous button's disabled state to be tied to next-page fetches; update the computed to call isFetchingPreviousPage() so the disabled state aligns with previous-page fetch activity and remains consistent with previousButtonText and the intended behavior.packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.ts lines 82 to 102Outdated@@ -91,3 +102,21 @@102+ class TestComponent {103+ query = injectInfiniteQuery(104+ () => ({105+ queryKey: ['manualInjector'],106+ queryFn: ({ pageParam }) =>107+ sleep(0).then(() => 'data on page ' + pageParam),108+ initialPageParam: 0,109+ getNextPageParam: () => 12,110+ }),111+ {112+ injector: injector,113+ },114+ )115+ }116+117+ const fixture = TestBed.createComponent(TestComponent)118+ fixture.detectChanges()119+ const query = fixture.componentInstance.query9112092121 expect(query.status()).toBe('pending')93122 })⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
Injection-context test no longer calls
injectInfiniteQueryoutside an injection contextIn
test('can be used outside injection context when passing an injector'),injectInfiniteQueryis now invoked inside a component constructor/field initializer, which already has an Angular injection context. The description suggests we still want to verify the "no injection context but manual injector" path.To keep that behavior covered, consider adding (or restoring) a direct call pattern alongside the component-based test, for example:
- @Component({ - selector: 'app-test', - template: '', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - }) - class TestComponent { - query = injectInfiniteQuery( - () => ({ - queryKey: ['manualInjector'], - queryFn: ({ pageParam }) => - sleep(0).then(() => 'data on page ' + pageParam), - initialPageParam: 0, - getNextPageParam: () => 12, - }), - { - injector: injector, - }, - ) - } + // Ensure calling injectInfiniteQuery outside an Angular injection + // context works when an explicit injector is provided. + expect(() => + injectInfiniteQuery( + () => ({ + queryKey: ['manualInjector'], + queryFn: ({ pageParam }) => + sleep(0).then(() => 'data on page ' + pageParam), + initialPageParam: 0, + getNextPageParam: () => 12, + }), + { injector }, + ), + ).not.toThrow()
I'll verify this review comment by examining the test file and understanding the injection context behavior.
```
🏁 Script executed:
#!/bin/bash # Examine the test file to see the full context and surrounding tests cat packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.tsLength of output: 3294
Add a direct test call outside injection context to match test description
The test "can be used outside injection context when passing an injector" calls
injectInfiniteQuery()inside a component's field initializer, which runs within Angular's automatic injection context. This contradicts the test's stated purpose.The first injection context test correctly demonstrates calling outside a context (and verifies it throws without an injector). The second test should actually verify that providing an explicit injector allows the call to succeed outside a context.
Add a direct call pattern to verify the manual injector works without relying on Angular's context:
test('can be used outside injection context when passing an injector', () => { const injector = TestBed.inject(Injector) + // Ensure calling injectInfiniteQuery outside an Angular injection + // context works when an explicit injector is provided. + expect(() => + injectInfiniteQuery( + () => ({ + queryKey: ['manualInjector'], + queryFn: ({ pageParam }) => + sleep(0).then(() => 'data on page ' + pageParam), + initialPageParam: 0, + getNextPageParam: () => 12, + }), + { injector }, + ), + ).not.toThrow() + @Component({🤖 Prompt for AI Agents
In packages/angular-query-experimental/src/__tests__/inject-infinite-query.test.ts around lines 93 to 122, the test claims to verify calling injectInfiniteQuery outside an injection context when passing an injector but currently calls it inside a component field initializer (an automatic injection context). Change the test to perform a direct call to injectInfiniteQuery outside any component: obtain the injector via TestBed.inject(Injector), then call injectInfiniteQuery(...) directly with the injector option (not inside a component) and assert the returned query behaves as expected (e.g., status() === 'pending'); remove or replace the component-based call so the test truly exercises manual injector usage outside Angular's automatic context.- Browser-only guard and
github-actions[bot](GitHub profile, opens in a new tab) added labelsdocumentation
How we can help on the PR?
I have been playing around with it in this personal repo with PRs and would love to contribute to get it out of experimental. What I have found out is:
- Pending Tasks:
await fixture.whenStable()will return immediately whileawait app.whenStable()does not, causing this issue: https://github.com/TanStack/query/issues/9910 . This might be fixed by starting the pending task right away in queries and avoiding a race condition in mutations. Testing can be done by addingexpect(fixture.isStable()).toBe(false)on any text with a component fixture where a pending state is expected. Signal Proxy: To keep the current API while avoiding problems when accessing the proxy, it is ideal to pass thought the proxy the array of functions it should not convert to signals. Here is a PR with the idea. I also played around chaining it to not transform the reactive proxy getters to functions that would improve type narrowing and reduce type complexity, but I understand that a "store pattern" like solid might not be appropriate with angular's conventions 🤔
- Pending Tasks:
:warning: Please install the
to ensure uploads and comments are reliably processed by Codecov.
Codecov Report#
:x: Patch coverage is
94.89051%with7 linesin your changes missing coverage. Please review. :white_check_mark: Project coverage is 94.48%. Comparing base (66a194e) to head (75cb8ca). :warning: Report is 600 commits behind head on main. :exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality.Additional details and impacted files
@@ Coverage Diff @@ ## main #9893 +/- ## =========================================== + Coverage 45.78% 94.48% +48.69% =========================================== Files 200 20 -180 Lines 8413 435 -7978 Branches 1922 99 -1823 =========================================== - Hits 3852 411 -3441 + Misses 4113 23 -4090 + Partials 448 1 -447Components Coverage Δ @tanstack/angular-query-experimental 94.23% <94.89%> (+0.37%):arrow_up: @tanstack/eslint-plugin-query ∅ <ø> (∅)@tanstack/query-async-storage-persister ∅ <ø> (∅)@tanstack/query-broadcast-client-experimental ∅ <ø> (∅)@tanstack/query-codemods ∅ <ø> (∅)@tanstack/query-core ∅ <ø> (∅)@tanstack/query-devtools ∅ <ø> (∅)@tanstack/query-persist-client-core ∅ <ø> (∅)@tanstack/query-sync-storage-persister ∅ <ø> (∅)@tanstack/query-test-utils ∅ <ø> (∅)@tanstack/react-query ∅ <ø> (∅)@tanstack/react-query-devtools ∅ <ø> (∅)@tanstack/react-query-next-experimental ∅ <ø> (∅)@tanstack/react-query-persist-client ∅ <ø> (∅)@tanstack/solid-query ∅ <ø> (∅)@tanstack/solid-query-devtools ∅ <ø> (∅)@tanstack/solid-query-persist-client ∅ <ø> (∅)@tanstack/svelte-query ∅ <ø> (∅)@tanstack/svelte-query-devtools ∅ <ø> (∅)@tanstack/svelte-query-persist-client ∅ <ø> (∅)@tanstack/vue-query ∅ <ø> (∅)@tanstack/vue-query-devtools ∅ <ø> (∅):rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
Closing in favor of the
angular-adapter-prebranch for@tanstack/angular-query@rcbenjavicente(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 75cb8ca643d5119b510002f36fddd414e1f0f81e
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR