代码之家  ›  专栏  ›  技术社区  ›  Rusty Rob

角异步重载微调器

  •  1
  • Rusty Rob  · 技术社区  · 6 年前

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

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

    但是,当用户再次搜索时,加载..不显示,我想我需要这个searchresults$observate发出null来再次显示微调器,或者有一个单独的isloading变量。

    最好的办法是什么?

    如果重要的话,我有一个debounce和一个switchmap(即使用finalize等很棘手)

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

    我也试过了 *ngIf="!isLoading && (searchResults$ | async) as searchResults 但发现它有问题,例如搜索结果$未订阅,或角度抱怨更改检测后的更改

    1 回复  |  直到 6 年前
        1
  •  2
  •   wilver    6 年前

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

    this.searchResults$ = merge(
          this.filters$.pipe(map(f => null)),
          this.filters$.pipe(
            debounceTime(200),
            distinctUntilChanged(),
            switchMap((f) => {
                return httpGet(f)
            })
          )
        );
    
        2
  •  1
  •   rh16    6 年前

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

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

    然后你可以通过将它放在一个不同的ngif中来绕过角度不订阅你的观测值。 ng-container 元素。

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