RxJS-使用forEach并等待所有完成的多个请求 [英] RxJS - Multiple Requests using forEach and waiting all to finish

查看:102
本文介绍了RxJS-使用forEach并等待所有完成的多个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

  • 首先,我打电话给服务部门,并获得了一份物品清单.(对象数组)
  • 对于此列表中的每个项目,我都会调用另一项服务,并且实际上它们都可以并行触发.
  • 我必须等待所有答案.当我得到所有答案时,我便有了最终的逻辑.

我现在有这样的事情,而没有正确使用RxJS:

I now have sth like this without using RxJS properly:

this.service.readArray().subscribe((array: Object[]) => {
  if (array.length > 0) {
    array.forEach((item, index) => {

      this.service2.readItem(item.id)
        .subscribe(details => {
          item.details = details;
          // manually finally logic
          if (index === array.length - 1) { // if the last iteration
            ...
          }
        }, (response: HttpErrorResponse) => {
            ...
          // manually finally logic also for error part
          if (index === array.length - 1) { // if the last iteration
          ... 
          }
        });

    });
  } else {
    ... logic for no items in list
  }
}, (error) => {
  ...
});

如何在Rxjs(5)语句中表示这一点?

How can i represent this in a Rxjs (5) statement?

推荐答案

您可以使用forkJoin等待所有调用完成.看起来您正在使用rxjs 5 [正如您在问题中提到的],因此让我们像这样更改代码[请参见代码注释中的描述]:

You can use forkJoin to wait for all the calls to get finished. Look like you are using rxjs 5 [as you mentioned in your question] so let's change the code like this [see the description in the code comments]:

this.service.readArray()
        .switchMap(array => {
          //lets map the array member to the respective observable
          const obs$ = array.map(item => {

             return this.service2.readItem(item.id)
                        .pipe(
                           catchError(err => {

                             //Do whatever you want to do with this error
                             //make sure to return an observable as per your logic. For this example, I am simply returning the err wrapped in an observable. Having catchError operator will gracefully handle the exception and make sure to emit the value as part of forkJoin.
                             return of(err);

                           })
                         )
          });
          //forkJoin will wait for all the readItem calls get finished.
          return forkJoin(obs$);
        })
        .subscribe((finalArray) => {
          //finalArray will be the array of object [an response of this.service2.readItem(item.id)]
          console.log(finalArray);
          //do whatever you want to do with the array
        });

编辑-根据OP的要求-掌握 readArray

EDIT - As asked by OP - To get hold of the response of readArray

this.service.readArray()
        .switchMap(array => {
          //lets map the array member to the respective observable
          const obs$ = array.map(item => {

             return this.service2.readItem(item.id)
                        .pipe(
                           catchError(err => {

                             //Do whatever you want to do with this error
                             //make sure to return an observable as per your logic. For this example, I am simply returning the err wrapped in an observable. Having catchError operator will gracefully handle the exception and make sure to emit the value as part of forkJoin.
                             return of(err);

                           })
                         )
          });
          //forkJoin will wait for all the readItem calls get finished.
          return forkJoin(obs$)
                  .pipe(
                    //return the original array along with joined using of
                    mergeMap((joined) => {
                      return of([array, joined]); 
                    })
                  );
        })
        .subscribe((finalArray) => {
          //finalArray will have readArray API response [i.e. array] at 0 index and on 1st index it will have joined array
          console.log(finalArray);
          //do whatever you want to do with the array
        });

这篇关于RxJS-使用forEach并等待所有完成的多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆