RxJS等待所有可观察对象完成第一次调用中的数据

时间:2019-02-12 09:22:59

标签: angular rxjs6

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

1 个答案:

答案 0 :(得分: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