如何设置角度路径参数管道的加载指示器*

问题描述 投票:0回答:2

我正在使用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'。

angular rxjs
2个回答
0
投票

除非您对Observable流有一定的了解,否则我不建议使用async管道。不要害怕简化并用更简单的运算符和技术来代替这些运算符和技术。

component.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));
  }

component.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>

-1
投票

尝试其他方法以获取您想要的内容。我在模拟HTTP请求或异步代码的items $中使用了delay和of。

  import { BehaviorSubject, of, Observable } from 'rxjs';
  import { delay, finalize, first } from 'rxjs/operators';

  items$: Observable<number[]> = of([1,2,3]).pipe(
    delay(2000),
    finalize(() => {
      this.isLoadingSubject.next(false)
    })
  );

  isLoadingSubject: BehaviorSubject<boolean> = new BehaviorSubject(true);

  isLoading$: Observable<boolean> = this.isLoadingSubject.asObservable();

  ngOnInit() {
    // first operator unsubscribe automatically
    this.items$.pipe(first()).subscribe();
  }
<div *ngIf="(isLoading$ | async); else itemsTemplate">
  Loading...
</div>
<ng-template #itemsTemplate>  
  <p>Items template</p>
  <div *ngFor="let item of items$ | async;">
   {{ item }}
  </div>
</ng-template>
© www.soinside.com 2019 - 2024. All rights reserved.