首页 > 解决方案 > Angular 4+ 对 http 调用的粒度控制以显示/隐藏加载器

问题描述

我有一个服务进行 http 调用并将数据作为 Observable 取回,我将它分配给组件中的一个变量,如下所示

this.usersResponse$ = this.dataSvc.getUsers(pageNumber);

在 html 上,我正在执行以下操作

<div *ngIf="usersResponse$ | async as userResponse; else loading">
    <ng-container>
        <ul>
            <li *ngFor="let user of userResponse.data" (click)="detail(user.id)">
                <img [src]="user.avatar" alt="">
                <p>{{ user.first_name }} {{ user.last_name }}</p>
            </li>
        </ul>
    </ng-container>    
</div>
<ng-template #loading>
    <app-loading></app-loading>
</ng-template>

我想要实现的是如何在 http 调用之前获得一个精细的控件来显示加载器,然后让 http 调用获取数据并关闭加载器,从而使 UI 变得跳跃。

我很感激帮助。

标签: angularrxjs6

解决方案


使用完成事件:

 this.showLoader=true;
this.usersResponse$ = this.dataSvc.getUsers(pageNumber);
this.usersResponse$.subscribe(null, null, () => 
this.showLoader=false);

在模板中

   <app-loading *ngIf="showLoader"></app-loading>

推荐阅读