首页 > 解决方案 > 外部完成时获取内部可观察对象

问题描述

我是 RxJS 的新手,所以我什至不确定我是否给了一个问题的正确标题。

解释我想要实现的目标:我有一个 API 端点,它会产生一组带有 id 的对象。然后,我将在多次调用中使用数组中的每个 id 调用另一个 API 端点。我希望第一个 API 的订阅者获取的数据已经包含第二个 API 调用的响应。

StackBlitz:https ://stackblitz.com/edit/rxjs-u45wvq

目前, 的值thatThing是可观察的 - 我希望它们成为接收到的对象。

编辑

我设法实现了我想要的,但在我看来它看起来很脏 - 因为解决方案使用Promise类来解决它。

https://stackblitz.com/edit/rxjs-d5ywen

如果有 RxJS 方法来做同样的事情,我会徘徊:

const source = fetchApi1().pipe(
  map(x => {
    return new Promise((yes, no) => {
      const s = x.array.map(m => fetchApi2(m.id))
      forkJoin(...s).subscribe(api2 => {
        x.array.forEach((row, i) => {
          row.thatThing = api2[i]
        })
        yes(x)
      })
    })
  }),
  switchMap(x => from(x))
);

标签: rxjs

解决方案


最好避免创建嵌套订阅,这样您就可以重写您所拥有的内容,例如以下内容:

const source = fetchApi1().pipe(
  mergeMap(x => {
    const s = x.array.map((m: any) => fetchApi2(m.id)
      .pipe(
        map(response => {
          m.thatThing = response;
          return m;
        }),
      ));

    return forkJoin(s).pipe(mapTo(x));
  }),
);

现场演示:https ://stackblitz.com/edit/rxjs-3nrc7g?file=index.ts


推荐阅读