angular 异步重新加载微调器

angular async reloading spinner

我有一个简单的设置来在异步管道为空时显示加载微调器:

<div *ngIf="(searchResults$ | async) as searchResults; else loading">
</div>
<ng-template #loading>
    loading..
</ng-template>

但是,当用户第二次再次搜索时,loading.. 没有显示,我想我需要这个 searchResults$ observable 发出 null 以再次显示微调器,或者有一个单独的 isLoading 变量。

最好的方法是什么?

如果重要的话,我有一个去抖动和一个 switchMap(即使用 finalize 等技巧)

this.searchResults$ = this.filters$
      .pipe(
        debounceTime(200),
        distinctUntilChanged(),
        switchMap((f) => {
            return httpGet(f)
        })
      )

另外,我试过 *ngIf="!isLoading && (searchResults$ | async) as searchResults 但发现它有问题,例如未订阅 searchResults$,或 angular 在更改检测后抱怨更改

我遇到了同样的问题并解决了区分 "ask" 流和 "result" 流的问题,将两者合并为可观察的组件结果。 像这样(基于您的代码):

this.searchResults$ = merge(
      this.filters$.pipe(map(f => null)),
      this.filters$.pipe(
        debounceTime(200),
        distinctUntilChanged(),
        switchMap((f) => {
            return httpGet(f)
        })
      )
    );

您可以尝试使用 tap 运算符设置 isLoading 变量,如下所示:

this.searchResults$ = this.filters$
      .pipe(
        debounceTime(200),
        distinctUntilChanged(),
        tap(() => {this.isLoading = true}),
        switchMap((f) => {
            return httpGet(f)
        }),
        tap(() => {this.isLoading = false})
      );

然后您可以通过将它托管在 ng-container 元素内的不同 *ngIf 中来绕过 angular 不订阅您的 observable。

<ng-container *ngIf="(searchResults$ | async) as searchResults">
  <div *ngIf="!isLoading"></div>
</ng-container>
<ng-template *ngIf="isLoading">
    loading..
</ng-template>