【问题标题】:RxJS Wait for all observables to finish with data from the first callRxJS 等待所有可观察对象完成第一次调用的数据
【发布时间】:2019-02-13 08:32:22
【问题描述】:

我需要从服务中获取数据。然后我需要遍历数据并使用我从第一次调用中获得的 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 的文档,但我不知道如何将它与第一次通话结合起来。非常感谢所有输入。

【问题讨论】:

标签: angular rxjs6


【解决方案1】:

你不需要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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 2019-04-23
相关资源
最近更新 更多