依赖查询(或串行查询)必须等待前面的查询完成后才能执行。要实现这一点,只需使用 enabled 选项来告诉查询何时准备好运行即可。
// 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,
}))
当 projects 查询开始时
status: 'pending'
isPending: true
fetchStatus: 'idle'
status: 'pending'
isPending: true
fetchStatus: 'idle'
一旦 user 可用,projects 查询就会被 enabled,然后过渡到
status: 'pending'
isPending: true
fetchStatus: 'fetching'
status: 'pending'
isPending: true
fetchStatus: 'fetching'
一旦我们有了项目,它将进入
status: 'success'
isPending: false
fetchStatus: 'idle'
status: 'success'
isPending: false
fetchStatus: 'idle'
动态并行查询 - injectQueries 也可以依赖于之前的查询,以下是如何实现这一点的方法:
// injectQueries is under development for Angular Query
// injectQueries is under development for Angular Query
请注意,injectQueries 返回一个查询结果数组。
顾名思义,依赖查询构成了请求瀑布的一种形式,这会损害性能。如果我们假设两个查询花费相同的时间,那么串行执行而不是并行执行总是需要两倍的时间,当发生在网络延迟很高的客户端上时,这种影响尤其严重。如果可能,最好重构后端 API,以便两个查询都可以并行获取,尽管这可能并不总是实际可行的。
在上面的示例中,与其先获取 getUserByEmail 来获取 getProjectsByUser,不如引入一个新的 getProjectsByUserEmail 查询来扁平化瀑布。