译零 TransZero · TanStack Query 中文文档
主站

默认查询函数

更新于 2026-11-02 Angular 查看英文原文 ↗

如果你出于任何原因希望为整个应用共享同一个查询函数,仅通过查询键(query keys)来标识它应拉取的内容,你可以通过向 TanStack Query 提供一个 默认查询函数(default query function) 来实现:

TypeScript
1// Define a default query function that will receive the query key2const defaultQueryFn: QueryFunction = async ({ queryKey }) => {3  const { data } = await axios.get(4    `https://jsonplaceholder.typicode.com${queryKey[0]}`,5  )6  return data7}8 9// provide the default query function to your app with defaultOptions10const queryClient = new QueryClient({11  defaultOptions: {12    queries: {13      queryFn: defaultQueryFn,14    },15  },16})17 18bootstrapApplication(MyAppComponent, {19  providers: [provideTanStackQuery(queryClient)],20})21 22export class PostsComponent {23  // All you have to do now is pass a key!24  readonly postsQuery = injectQuery<Array<Post>>(() => ({25    queryKey: ['/posts'],26  }))27  // ...28}29 30export class PostComponent {31  // You can even leave out the queryFn and just go straight into options32  readonly postQuery = injectQuery<Post>(() => ({33    enabled: this.postIdSignal() > 0,34    queryKey: [`/posts/${this.postIdSignal()}`],35  }))36  // ...37}

如果你需要覆盖默认的 queryFn,只需像平常一样提供你自己的 queryFn 即可。