( optionsFn: () => InjectQueriesOptions<T, TCombinedResult>, injector?: Injector, )
| 218 | * @param injector - The Angular injector to use. |
| 219 | */ |
| 220 | export function injectQueries< |
| 221 | T extends Array<any>, |
| 222 | TCombinedResult = QueriesResults<T>, |
| 223 | >( |
| 224 | optionsFn: () => InjectQueriesOptions<T, TCombinedResult>, |
| 225 | injector?: Injector, |
| 226 | ): Signal<TCombinedResult> { |
| 227 | !injector && assertInInjectionContext(injectQueries) |
| 228 | return runInInjectionContext(injector ?? inject(Injector), () => { |
| 229 | const destroyRef = inject(DestroyRef) |
| 230 | const ngZone = inject(NgZone) |
| 231 | const queryClient = inject(QueryClient) |
| 232 | const isRestoring = injectIsRestoring() |
| 233 | |
| 234 | /** |
| 235 | * Signal that has the default options from query client applied |
| 236 | * computed() is used so signals can be inserted into the options |
| 237 | * making it reactive. Wrapping options in a function ensures embedded expressions |
| 238 | * are preserved and can keep being applied after signal changes |
| 239 | */ |
| 240 | const optionsSignal = computed(() => { |
| 241 | return optionsFn() |
| 242 | }) |
| 243 | |
| 244 | const defaultedQueries = computed(() => { |
| 245 | return optionsSignal().queries.map((opts) => { |
| 246 | const defaultedOptions = queryClient.defaultQueryOptions( |
| 247 | opts as QueryObserverOptions, |
| 248 | ) |
| 249 | // Make sure the results are already in fetching state before subscribing or updating options |
| 250 | defaultedOptions._optimisticResults = isRestoring() |
| 251 | ? 'isRestoring' |
| 252 | : 'optimistic' |
| 253 | |
| 254 | return defaultedOptions as QueryObserverOptions |
| 255 | }) |
| 256 | }) |
| 257 | |
| 258 | const observerSignal = (() => { |
| 259 | let instance: QueriesObserver<TCombinedResult> | null = null |
| 260 | |
| 261 | return computed(() => { |
| 262 | return (instance ||= new QueriesObserver<TCombinedResult>( |
| 263 | queryClient, |
| 264 | defaultedQueries(), |
| 265 | optionsSignal() as QueriesObserverOptions<TCombinedResult>, |
| 266 | )) |
| 267 | }) |
| 268 | })() |
| 269 | |
| 270 | const optimisticResultSignal = computed(() => |
| 271 | observerSignal().getOptimisticResult( |
| 272 | defaultedQueries(), |
| 273 | (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine, |
| 274 | ), |
| 275 | ) |
| 276 | |
| 277 | // Do not notify on updates because of changes in the options because |
searching dependent graphs…