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