当异步作业完成时,如何指示UI组件



我有一个与视图组件进行通信的经理类,并且该管理器类具有在返回值之前执行一堆API调用的方法,因此我希望组件有一些何时API调用结束的指示器,因为我需要在数据仍在继续时禁用一些按钮,因此:

export class MyManager {
 public stillBringingData = new BehaviorSubject<boolean>(false);

 public myAsyncFunc(animals: Animal[]): void {
    let counter: number = 0;
    animals.forEach((animal: Animal) => {
      counter++;
      this._myApService.getAnimalInfo(animal.id).subscribe((animalInfo: AnimalInfo) => {
        //currentAnimalInfo is some behaviour subject hat the client listen too
        this.currentAnimalInfo.next(animalInfo)
      });
      this.stillBringingData.next(counter === animals.length)
    });
  }

} 

和UI组件以订阅方式聆听此行为主题。

感觉有点笨拙,有更经典的方式吗?

使用Angular 4/observables/tyspript

谢谢

进度指标我在Angular版本4:nprogress
中使用精确版本:" ngx-progressbar":"^2.0.4"。github源
如何整合?
1) in app.component.html
放置标题的部分:

<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1"
             [speed]="200" [showSpinner]="true" [direction]="'leftToRightIncreased'"
             [color]="'#5be7cb'" [trickleSpeed]="250" [thick]="true" [ease]="'linear'"
></ng-progress>

2)在要显示指示器的组件中:
import { NgProgressService } from 'ngx-progressbar';
constructor(private progressService: NgProgressService)

3)在async操作开始(通常是http呼叫): this.progressService.start();
异步动作结束的地方: this.progressService.done();

或者,如果要绑定按钮状态boolean绑定到 button 时,ASYNC操作结束时自动将状态更改为disabled or enabled,有必要创建一个公共布尔字段: public isActionExecuting: boolean;在异步调用开始时,将此属性设置为 true,并在订阅内部设置:

this._myApService.getAnimalInfo(animal.id).subscribe((animalInfo: AnimalInfo) => { 
    //some stuff
    this.isActionExecuting = false;
    //other stuff
    //if other async stuff starts here, then inside the subscription of that async should mark with false
})

拥有, html 您可以绑定按钮禁用属性:

<button type="button" class="btn btn-primary btn-action"
              [disabled]="isActionExecuting"
              (click)="startAsyncAction()">Start Async Action</button>

最新更新