angular - 一旦所有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$
。
解决方案
forkJoin
真的是这里最好的选择。您只需将其链接起来map
以计算您需要的任何内容。
$totalEmitter$ = forkJoin([
amountOne$,
amountTwo$,
]).pipe(
map(([result1, result2]) => /* do calcualtions */)
);
推荐阅读
- c - 为我的二进制可执行文件获取错误的足迹
- python - python解析文件并提取段落
- microsoft-translator - Microsoft Translator API / Web Translator 的不同结果
- mongodb - 使用 SpringBoot 从本地机器连接到 Mongo(托管在 VM 上)
- r - 使用 R 中 Raster 包中的分位数函数计算栅格堆栈的第一个和第三个四边形
- excel - 从 url 超链接下载文件
- c++ - 如何使用 doxygen 记录我的 cpp 函数?
- ruby - golang调用ruby dll
- r - 来自排名数据的概率密度图
- java - 在 screen_on 上更新 android 小部件的最佳方法是什么。Android Oreo (API 26) 是否支持