Open History to see the last commit
1import { DestroyRef, NgZone, inject, signal } from '@angular/core'
2import { QueryClient, notifyManager } from '@tanstack/query-core'
3import { assertInjector } from './util/assert-injector/assert-injector'
4import type { QueryFilters } from '@tanstack/query-core'
5import type { Injector, Signal } from '@angular/core'
6β
7/**
8 * Injects a signal that tracks the number of queries that your application is loading or
9 * fetching in the background.
10 *
11 * Can be used for app-wide loading indicators
12 * @param filters - The filters to apply to the query.
13 * @param injector - The Angular injector to use.
14 * @returns signal with number of loading or fetching queries.
15 * @public
16 */
17export function injectIsFetching(
18 filters?: QueryFilters,
19 injector?: Injector,
20): Signal<number> {
21 return assertInjector(injectIsFetching, injector, () => {
22 const destroyRef = inject(DestroyRef)
23 const ngZone = inject(NgZone)
24 const queryClient = inject(QueryClient)
25β
26 const cache = queryClient.getQueryCache()
27 // isFetching is the prev value initialized on mount *
28 let isFetching = queryClient.isFetching(filters)
29β
30 const result = signal(isFetching)
31β
32 const unsubscribe = ngZone.runOutsideAngular(() =>
33 cache.subscribe(
34 notifyManager.batchCalls(() => {
35 const newIsFetching = queryClient.isFetching(filters)
36 if (isFetching !== newIsFetching) {
37 // * and update with each change
38 isFetching = newIsFetching
39 ngZone.run(() => {
40 result.set(isFetching)
41 })
42 }
43 }),
44 ),
45 )
46β
47 destroyRef.onDestroy(unsubscribe)
48β
49 return result
50 })
51}