You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RxJS操作符中如何在switchMap后的tap中获取index值?

解决RxJS中switchMap后tap无法获取原始index的问题

你可以在switchMap内部通过map操作符把原始的index和API请求返回的list打包成一个对象(或数组),这样下游的tap就能同时拿到这两个值了。

修改后的代码如下:

this.checkListSubject
  .pipe(
    takeUntil(this._unSubscribeAll),
    filter((filter) => !!filter),
    switchMap((index) => 
      // 在API请求的Observable管道里,把index和结果打包
      this._api.get('getMyData').pipe(
        map(list => ({ index, list }))
      )
    ),
    // 解构拿到index和list
    tap(({ index, list }) => this.gateEditArrayModal.toArray()[index].display(list))
  )
  .subscribe();

原理很简单:switchMap会将上游的index转换为新的Observable(也就是API请求的结果),默认情况下只会传递请求返回的list。通过在switchMap内部的子管道里用map把index和list组合起来,就能把原始的index保留并传递到下游的tap中。

内容的提问来源于stack exchange,提问作者user2837961

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:10:17