首页 > 解决方案 > 如何为 Angular 路由参数管道设置加载指示器*

问题描述

我正在使用角度和 rxjs。我的问题是显示加载指示器

  isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false);

  ngOnInit() {
    this.items = this.route.paramMap.pipe(
      tap(() => this.isLoading.next(true)),
      switchMap((params: ParamMap) => this.myservice.getItems(params.get("id"))),
      tap(() => this.isLoading.next(false))
    )
  }

html是:

 <i class="spinner" *ngIf="(isLoading | async)"></i>
 <div *ngIf="!(isLoading | async)">
    <grid *ngFor="let item of items | async;" [item]="item">
      ...
    </grid>
 </div>

但是这段代码抛出了一个异常。

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf: [object Object]'。当前值:'ngIf: true'。

标签: angularrxjs

解决方案


async除非您牢牢掌握 Observable 流,否则我建议不要使用管道。不要害怕简化并用更简单的操作符和技术替换花哨的操作符和技术。

组件.ts

 isLoading: boolean = false;
 ngOnInit() {
    this.isLoading = true;

    this.route.paramMap.pipe(
        switchMap((params: ParamMap) => this.myservice.getItems(params.get("id"))),
    ).subscribe((result: any) => {
        this.items = result;
        this.isLoading = false;
    }, ((error: any) => this.isLoading = false));
  }

组件.html:

看起来您正在尝试为每个项目创建一个网格实例?如果是这样,Item(单数)在这里是一个奇怪的名字。

<i class="spinner" *ngIf="isLoading"></i>
<div *ngIf="!isLoading">
    <ng-container *ngFor="let item of items">
        <grid [item]="item">
          ...
        </grid>
    </ng-container>
</div>

推荐阅读