从管道和内部可观察对象中获取价值

get value from piped and inner observable

我有以下代码,我想从商店获取商品,对该值应用一个函数,return商店的价值和修改后的价值

this.store$.pipe(select(carPositions), take(1)).pipe(
   mergeMap(positions => modify(positions))))
).subscribe((original, modified) => {
    //do some stuff
})

问题是,上面的代码return只是修改的,不是原来的

怎么了?

使用 combineLatest 委托 positions,来自他们的文档:

When any observable emits a value, emit the last emitted value from each.

你应该是:

this.store$
  .pipe(
    select(carPositions),
    take(1),
    mergeMap(positions => {
      return combineLatest(of(positions), modify(positions));
    })
  )
  .subscribe(([original, modified]) => {
    //do some stuff
  });

我假设 modify(positions) return 是一个 Observable,否则 mergeMap 将无法工作。

如果是这种情况,你可以尝试这样的事情(阅读内联评论了解一些细节)

this.store$.pipe(
  select(carPositions), 
  take(1),
  mergeMap(positions => modify(positions).pipe(
       // map the notification of modify so that it returns also the positions in a tuple
       map(modified => {
          return [positions, modified]
       })
    )
  )
)
// the value emitted is the tuple generated above
.subscribe(([positions, modified]) => {
    //do some stuff
})

您基本上使用 map 运算符使用参数 positionsmodify(positions) 发出的结果丰富为 return 具有两个值的元组。这是使用 rxjs 时的典型模式。