我需要从服务中获取数据。然后我需要遍历数据并使用我从第一次调用获得的id获取数据。
我的目标是在加载所有数据时通过在ChangeDetectorRef上调用markForCheck()来优化Angular绑定性能。
这是我目前的代码。它完成了工作。但是在加载所有数据之前完成对markForCheck()的调用。
this.subs.push(
this.supplierService
.supplier(this.supplierId)
.pipe(
tap(supplier => {
this.subs.push(
of(supplier.employees.map(emp => emp.authId))
.pipe(
mergeMap(ids => ids.map(id => this.authRegisterService.lookupId(id))),
mergeMap(res => res)
)
.subscribe(
result => {
this.authRegs.push(result);
},
error => {
this.toastr.error(error);
return EMPTY;
}
)
);
}),
tap(supplier => {
this.subs.push(this.cvrService.getCompany(supplier.cvr).subscribe(cvr => (this.cvr = cvr)));
}),
tap(supplier => {
this.subs.push(
of(supplier.locations.map(loc => loc.sorId))
.pipe(
mergeMap(ids => ids.map(id => this.sorService.getLocation(id))),
mergeMap(res => res)
)
.subscribe(sor => {
this.sors.push(sor);
})
);
})
)
.subscribe(supplier => {
this.supplier = supplier;
this.supplierStatusLabel = SupplierStatusNames.get(supplier.status);
this.cd.markForCheck();
})
);
我阅读了forkJoin的文档,但我不知道如何将它与第一次调用结合起来。所有输入都非常感激。
你不需要forkJoin,你需要mergeMap或concatMap,forkJoin通常是坏的,为什么?,因为如果一个请求失败,那么,其他一切都失败了。
mergeMap和concatMap如果十个请求中的一个请求失败,则其他九个请求继续尝试完成。
mergeMap和concatMap之间的区别在于它们执行请求的方式,在mergeMap中它们以“一键推送”发送到服务器,我的意思是,让我们想要提取10个日期,mergeMap然后执行10个日期的请求无需等待前一个完成,而concatMap等待前一个完成向队列添加新请求。
这里有一个“如何使用concatMap,mergeMap和forkJoin”的例子:https://angular-bojdob.stackblitz.io
我写了一篇中文帖子,但是用西班牙文写的,但是关于这个也有一个非常好的媒体帖子:这里是西班牙语(我的):https://medium.com/@asfo/usando-concatmap-mergemap-y-forkjoin-en-angular-para-peticiones-http-c70f65df54af
这是来自Tomas(英语):https://blog.angularindepth.com/practical-rxjs-in-the-wild-requests-with-concatmap-vs-mergemap-vs-forkjoin-11e5b2efe293