一个查询的 status === 'pending' 状态足以显示查询的初始硬加载状态,但有时你可能想要显示一个额外的指示器,表明查询正在后台重新获取。为此,查询还为您提供了一个 isFetching 布尔值,您可以使用它来显示它处于获取状态,而不管 status 变量的状态如何
@Component({
selector: 'todos',
template: `
@if (todosQuery.isPending()) {
Loading...
} @else if (todosQuery.isError()) {
An error has occurred: {{ todosQuery.error().message }}
} @else if (todosQuery.isSuccess()) {
@if (todosQuery.isFetching()) {
Refreshing...
}
@for (todos of todosQuery.data(); track todo.id) {
<todo [todo]="todo" />
}
}
`,
})
class TodosComponent {
todosQuery = injectQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodos,
}))
}
@Component({
selector: 'todos',
template: `
@if (todosQuery.isPending()) {
Loading...
} @else if (todosQuery.isError()) {
An error has occurred: {{ todosQuery.error().message }}
} @else if (todosQuery.isSuccess()) {
@if (todosQuery.isFetching()) {
Refreshing...
}
@for (todos of todosQuery.data(); track todo.id) {
<todo [todo]="todo" />
}
}
`,
})
class TodosComponent {
todosQuery = injectQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodos,
}))
}
除了单独的查询加载状态之外,如果您想在任何查询正在获取时(包括在后台)显示全局加载指示器,则可以使用 useIsFetching hook
import { injectIsFetching } from '@tanstack/angular-query-experimental'
@Component({
selector: 'global-loading-indicator',
template: `
@if (isFetching()) {
<div>Queries are fetching in the background...</div>
}
`,
})
export class GlobalLoadingIndicatorComponent {
isFetching = injectIsFetching()
}
import { injectIsFetching } from '@tanstack/angular-query-experimental'
@Component({
selector: 'global-loading-indicator',
template: `
@if (isFetching()) {
<div>Queries are fetching in the background...</div>
}
`,
})
export class GlobalLoadingIndicatorComponent {
isFetching = injectIsFetching()
}