angular - 如何为 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'。
解决方案
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>
推荐阅读
- javascript - 如何将用户 ID 字符串键入用户对象
- python - 环境变量未在 vs 代码中使用
- pandas - 加入/合并熊猫数据帧,其中索引是其他索引的子字符串
- javascript - JavaScript 中的串联继承与类继承
- javascript - 如何使用 JQUERY/AJAX 显示包含图片和文本数据的多个数据,这些数据作为对象或数组发送?
- java - Gradle 在多模块 micronaut 项目上运行失败
- python - 如何在 python 中更改 PysimpleGUI 中的弹出窗口大小?
- php - 在 Laravel 中按名称过滤是否正确?
- python - 如何将枚举算法应用到问题中?
- javascript - liquibase mongodb 从 liquibase 运行一个 js 脚本文件作为更改集