首页 > 解决方案 > 一旦所有http调用以角度完成后计算总数

问题描述

我们有一个“仪表板”,我们在其中发出多个 http 请求,每个请求都返回仪表板一部分的数据。我现在需要的是计算每个部分调用的总数。

这些调用中的每一个都分配给一个变量,并使用async pipe.

我正在考虑使用forkJoin合并所有调用,然后调用complete函数上的方法来计算总数。

例如:

amountOne$: Observable<IAmounts>; 
amountTwo$: Observable<IAmounts>; 


this.amountOne$ = httpCall();
this.amountTwo$ = httpCall();

<ng-container *ngIf='amountOne$ | async as amountOne;'>...</ng-container>
<ng-container *ngIf='amountTwo$ | async as amountTwo;'>...</ng-container>

我目前拥有的是这个...

 totalEmitter$ = new BehaviorSubject<number>(0);

然后每次调用都会调用这个函数:

  private calcTotal() {

     let calc = 0;
     if (this.amountOne$) {
       calc += this.amountOne$.total;
     }

     if (this.amountTwo$) {
       calc += this.amountTwo$.total;
     }

     this.totalEmitter$.next(calc);
  }

<h2>Total: {{totalEmitter$| async | number : '1.2-2'}}</h2>

这在我开始使用 observables 之前就可以工作了,但是我在每次调用后都调用了这个函数,我更愿意在我知道一切都完成后调用它。我只是想弄清楚这种场景的最佳方法是什么。

编辑:在@martin 的建议下使用 forkJoin

totalEmitter$: Observable<number>;

totalEmitter$ = forkJoin([
  amountOne$,
  amountTwo$,
]).pipe(
  map(([result1, result2]) => /* do calcualtions */)
);

totalEmitter$now 具有正确的值,但它现在对 and 进行了额外的httpamountOne$调用amountTwo$

标签: angularrxjs

解决方案


forkJoin真的是这里最好的选择。您只需将其链接起来map以计算您需要的任何内容。

$totalEmitter$ = forkJoin([
  amountOne$,
  amountTwo$,
]).pipe(
  map(([result1, result2]) => /* do calcualtions */)
);

推荐阅读