Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions examples/angular/router/src/app/components/post.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@ export default class PostComponent {
#postsService = inject(PostsService)
queryClient = injectQueryClient()

postId = input(0, {
postId = input.required({
transform: numberAttribute,
})

postQuery = injectQuery(() => ({
enabled: this.postId() > 0,
queryKey: ['post', this.postId()],
queryFn: () => {
return lastValueFrom(this.#postsService.postById$(this.postId()))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TestBed, fakeAsync, flush } from '@angular/core/testing'
import { TestBed, fakeAsync, flush, tick } from '@angular/core/testing'
import { QueryClient } from '@tanstack/query-core'
import { beforeEach, describe, expect } from 'vitest'
import { injectIsFetching } from '../inject-is-fetching'
Expand All @@ -25,6 +25,9 @@ describe('injectIsFetching', () => {
}))
return injectIsFetching()
})

tick()

expect(isFetching()).toStrictEqual(1)
flush()
expect(isFetching()).toStrictEqual(0)
Expand Down
94 changes: 49 additions & 45 deletions packages/angular-query-experimental/src/create-base-query.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import {
DestroyRef,
assertInInjectionContext,
Injector,
computed,
effect,
inject,
runInInjectionContext,
signal,
untracked,
} from '@angular/core'
import { notifyManager } from '@tanstack/query-core'
import { signalProxy } from './signal-proxy'
import { lazyInit } from './lazy-init'
import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'

Expand All @@ -34,54 +36,56 @@ export function createBaseQuery<
Observer: typeof QueryObserver,
queryClient: QueryClient,
): CreateBaseQueryResult<TData, TError> {
assertInInjectionContext(createBaseQuery)
const destroyRef = inject(DestroyRef)
const injector = inject(Injector)

/**
* Signal that has the default options from query client applied
* computed() is used so signals can be inserted into the options
* making it reactive. Wrapping options in a function ensures embedded expressions
* are preserved and can keep being applied after signal changes
*/
const defaultedOptionsSignal = computed(() => {
const defaultedOptions = queryClient.defaultQueryOptions(
options(queryClient),
)
defaultedOptions._optimisticResults = 'optimistic'
return defaultedOptions
})
return lazyInit(() => {
return runInInjectionContext(injector, () => {
const destroyRef = inject(DestroyRef)
/**
* Signal that has the default options from query client applied
* computed() is used so signals can be inserted into the options
* making it reactive. Wrapping options in a function ensures embedded expressions
* are preserved and can keep being applied after signal changes
*/
const defaultedOptionsSignal = computed(() => {
const defaultedOptions = queryClient.defaultQueryOptions(
options(queryClient),
)
defaultedOptions._optimisticResults = 'optimistic'
return defaultedOptions
})

const observer = new Observer<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>(queryClient, defaultedOptionsSignal())
const observer = new Observer<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>(queryClient, defaultedOptionsSignal())

const resultSignal = signal(
observer.getOptimisticResult(defaultedOptionsSignal()),
)
const resultSignal = signal(
observer.getOptimisticResult(defaultedOptionsSignal()),
)

effect(() => {
const defaultedOptions = defaultedOptionsSignal()
observer.setOptions(defaultedOptions, {
// Do not notify on updates because of changes in the options because
// these changes should already be reflected in the optimistic result.
listeners: false,
})
untracked(() =>
// Set the signal in effect because it's both 'computed' from options()
// and needs to be set imperatively in the query observer listener.
resultSignal.set(observer.getOptimisticResult(defaultedOptions)),
)
})
effect(() => {
const defaultedOptions = defaultedOptionsSignal()
observer.setOptions(defaultedOptions, {
// Do not notify on updates because of changes in the options because
// these changes should already be reflected in the optimistic result.
listeners: false,
})
untracked(() => {
resultSignal.set(observer.getOptimisticResult(defaultedOptions))
})
})

// observer.trackResult is not used as this optimization is not needed for Angular
const unsubscribe = observer.subscribe(
notifyManager.batchCalls((val) => resultSignal.set(val)),
)
destroyRef.onDestroy(unsubscribe)
// observer.trackResult is not used as this optimization is not needed for Angular
const unsubscribe = observer.subscribe(
notifyManager.batchCalls((val) => resultSignal.set(val)),
)
destroyRef.onDestroy(unsubscribe)

return signalProxy(resultSignal) as CreateBaseQueryResult<TData, TError>
return signalProxy(resultSignal) as CreateBaseQueryResult<TData, TError>
})
})
}
34 changes: 34 additions & 0 deletions packages/angular-query-experimental/src/lazy-init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export function lazyInit<T extends object>(initializer: () => T): T {
let object: T | null = null

const initializeObject = () => {
if (!object) {
object = initializer()
}
}

Promise.resolve().then(() => {
initializeObject()
})

return new Proxy<T>({} as T, {
get(_, prop, receiver) {
initializeObject()
return Reflect.get(object as T, prop, receiver)
},
has(_, prop) {
initializeObject()
return Reflect.has(object as T, prop)
},
ownKeys() {
initializeObject()
return Reflect.ownKeys(object as T)
},
getOwnPropertyDescriptor() {
return {
enumerable: true,
configurable: true,
}
},
})
}