查询选项
在多个位置之间共享 queryKey 和 queryFn,同时又让它们彼此就近共置,其中一种最佳方式是使用 queryOptions 辅助函数。该辅助函数在运行时仅返回你传入的任何内容,但 配合 TypeScript 使用时 具备诸多优势:你可以在一个地方定义某个查询的所有可能选项,并且能为所有这些选项获得类型推断和类型安全。
TypeScript
1import { queryOptions, noop } from '@tanstack/angular-query-experimental'2 3@Injectable({4 providedIn: 'root',5})6export class QueriesService {7 private readonly http = inject(HttpClient)8 9 post(postId: number) {10 return queryOptions({11 queryKey: ['post', postId],12 queryFn: () => {13 return lastValueFrom(14 this.http.get<Post>(15 `https://jsonplaceholder.typicode.com/posts/${postId}`,16 ),17 )18 },19 })20 }21}22 23// usage:24 25postId = input.required({26 transform: numberAttribute,27})28queries = inject(QueriesService)29 30postQuery = injectQuery(() => this.queries.post(this.postId()))31 32queryClient.query(this.queries.post(23)).catch(noop)33queryClient.setQueryData(this.queries.post(42).queryKey, newPost)对于无限查询(infinite query),另有单独的 infiniteQueryOptions 辅助函数可用。
你仍可在组件级别覆盖部分选项。一种非常常见且实用的模式是为每个组件创建专属的 select 函数:
TypeScript
1// Type inference still works, so postQuery.data will be the return type of select instead of queryFn2queries = inject(QueriesService)3 4postQuery = injectQuery(() => ({5 ...this.queries.post(1),6 select: (data) => data.title,7}))