依赖查询

injectQuery 依赖查询

依赖(或串行)查询依赖于先前的查询完成才能执行。为了实现这一点,只需使用 enabled 选项来告知查询何时准备好运行

ts
// Get the user
userQuery = injectQuery(() => ({
  queryKey: ['user', email],
  queryFn: getUserByEmail,
}))

// Then get the user's projects
projectsQuery = injectQuery(() => ({
  queryKey: ['projects', this.userQuery.data()?.id],
  queryFn: getProjectsByUser,
  // The query will not execute until the user id exists
  enabled: !!this.userQuery.data()?.id,
}))
// Get the user
userQuery = injectQuery(() => ({
  queryKey: ['user', email],
  queryFn: getUserByEmail,
}))

// Then get the user's projects
projectsQuery = injectQuery(() => ({
  queryKey: ['projects', this.userQuery.data()?.id],
  queryFn: getProjectsByUser,
  // The query will not execute until the user id exists
  enabled: !!this.userQuery.data()?.id,
}))

The projects 查询将以...

tsx
status: 'pending'
isPending: true
fetchStatus: 'idle'
status: 'pending'
isPending: true
fetchStatus: 'idle'

一旦 user 可用,projects 查询将被 enabled,然后过渡到...

tsx
status: 'pending'
isPending: true
fetchStatus: 'fetching'
status: 'pending'
isPending: true
fetchStatus: 'fetching'

一旦我们有了 projects,它将变为...

tsx
status: 'success'
isPending: false
fetchStatus: 'idle'
status: 'success'
isPending: false
fetchStatus: 'idle'

injectQueries 依赖查询

动态并行查询 - injectQueries 也可以依赖于先前的查询,以下是如何实现这一点

ts
// injectQueries is under development for Angular Query
// injectQueries is under development for Angular Query

请注意injectQueries 返回一个查询结果数组

关于性能的说明

依赖查询从定义上构成了一种 请求瀑布 的形式,这会损害性能。如果我们假设两个查询花费的时间相同,那么串行执行而不是并行执行总是花费两倍的时间,当这种情况发生在具有高延迟的客户端上时尤其有害。如果可以,最好重构后端 API,以便可以并行获取两个查询,但这可能并不总是实际可行的。

在上面的示例中,与其首先获取 getUserByEmail 以便能够 getProjectsByUser,不如引入一个新的 getProjectsByUserEmail 查询,这将扁平化瀑布。