Open History to see the last commit
1import {
2 DestroyRef,
3 Injector,
4 NgZone,
5 assertInInjectionContext,
6 inject,
7 signal,
8} from '@angular/core'
9import { QueryClient, notifyManager } from '@tanstack/query-core'
10import type { QueryFilters } from '@tanstack/query-core'
11import type { Signal } from '@angular/core'
12β
13/** Options for `injectIsFetching`, passed after the query filters. */
14export interface InjectIsFetchingOptions {
15 /**
16 * The `Injector` in which to create the isFetching signal.
17 *
18 * If this is not provided, the current injection context will be used instead
19 * (via `inject`).
20 */
21 injector?: Injector
22}
23β
24/**
25 * Injects a signal that tracks the number of queries that your application is
26 * loading or fetching in the background (useful for app-wide loading
27 * indicators).
28 *
29 * @example
30 * ```angular-ts
31 * @Component({
32 * selector: 'posts-fetching-indicator',
33 * template: `
34 * @if (isFetchingPosts()) {
35 * <span>Refreshing posts...</span>
36 * }
37 * `,
38 * })
39 * export class PostsFetchingIndicator {
40 * // How many queries matching the posts prefix are fetching?
41 * readonly isFetchingPosts = injectIsFetching({ queryKey: ['posts'] })
42 * }
43 * ```
44 *
45 * @example
46 * A global loading indicator for any query fetching in the background, not just the ones on screen:
47 * ```angular-ts
48 * @Component({
49 * selector: 'global-loading-indicator',
50 * template: `
51 * @if (isFetching()) {
52 * <div>Queries are fetching in the background...</div>
53 * }
54 * `,
55 * })
56 * export class GlobalLoadingIndicator {
57 * readonly isFetching = injectIsFetching()
58 * }
59 * ```
60 *
61 * @param filters - The {@link QueryFilters} to narrow down the matched queries.
62 * @param options - Additional configuration
63 * @returns A `Signal` with the number of queries that your application is
64 * currently loading or fetching in the background.
65 */
66export function injectIsFetching(
67 filters?: QueryFilters,
68 options?: InjectIsFetchingOptions,
69): Signal<number> {
70 !options?.injector && assertInInjectionContext(injectIsFetching)
71 const injector = options?.injector ?? inject(Injector)
72 const destroyRef = injector.get(DestroyRef)
73 const ngZone = injector.get(NgZone)
74 const queryClient = injector.get(QueryClient)
75β
76 const cache = queryClient.getQueryCache()
77 // isFetching is the prev value initialized on mount *
78 let isFetching = queryClient.isFetching(filters)
79β
80 const result = signal(isFetching)
81β
82 const unsubscribe = ngZone.runOutsideAngular(() =>
83 cache.subscribe(
84 notifyManager.batchCalls(() => {
85 const newIsFetching = queryClient.isFetching(filters)
86 if (isFetching !== newIsFetching) {
87 // * and update with each change
88 isFetching = newIsFetching
89 ngZone.run(() => {
90 result.set(isFetching)
91 })
92 }
93 }),
94 ),
95 )
96β
97 destroyRef.onDestroy(unsubscribe)
98β
99 return result
100}