文章内容

2020/11/17 11:39:59,作 者: 黄兵

Angular subscribe loading

最近在使用Angular rxjs的时候,获取数据的时候,页面显示增加加载,代码如下:

article.component.html

<div class="page-loading" *ngIf="isLoading$ | async">
<mat-spinner></mat-spinner>
</div>
<table *ngIf="!(isLoading$ | async)" mat-table [dataSource]="dataSource"
class="mat-elevation-z8">
</table>

为了简化起见,删除了部分不相关代码。

article.component.ts

export class AmericaArticleComponent implements OnInit, OnDestroy {
dataSource: any;
isLoading$: BehaviorSubject<boolean> = new BehaviorSubject(false);

ngOnInit() {
// 获取所有文章
this.getAllArticle();
}

getAllArticle() {
this.isLoading$.next(true);
this.sub = this.articleService.getArticle().subscribe(res => {
this.dataSource = res.americaArticleResult;
}, error => {
this.error = error;
}, () => {
this.isLoading$.next(false);
});
}

ngOnDestroy() {
if (this.sub) {
this.sub.unsubscribe();
}
}
}

这里使用BehaviorSubject()的方式发送状态。


参考资料:

1、Angular 2 - Show loading-information when (observableData | async) is not yet resolved


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Angular subscribe loading

分享到:

发表评论

评论列表