如何在 rxjs 中的订阅中重构订阅

How to refactor a subscribe inside a subscribe in rxjs

例如:

this.saveSubscription$ = this.ds.onSave$.subscribe(x => 
  this.sb.updateMachineTool(this.viewEditModel.viewEditModel).subscribe(x = {
    console.log('alert results', x)
  })
)

this.ds.onSave$ 是在单击不同组件上的保存按钮时触发的主题。

this.sb.updateMachineTool 是一个更新特定工具的 httpClient post

我应该使用某种类型的地图以便不订阅这两个区域吗?

如何重构此代码?

要重构您的代码,您可以使用
mergeMap
switchMap

您的问题是 switchMap 的完美用例。因为正如您所提到的,this.ds.onSave$ 是一个在单击不同组件上的保存按钮时触发的主题。
switchMap 在这种情况下给你的好处是,如果重复单击按钮,它会自动取消所有旧订阅(在你的情况下是正在进行的 Http 调用)。

修改代码

this.saveSubscription$ = this.ds.onSave$.pipe(switchMap(()=> 
  this.sb.updateMachineTool(this.viewEditModel.viewEditModel)
  )
).subscribe(x = {
    console.log('alert results', x)
  });

更多

  1. Understanding mergeMap and switchMap in RxJS
  2. The Simple Difference Between RxJS switchMap and mergeMap