如何在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.ds.onSave$
is a subject that triggers when a save button on a different component is clicked.
this.sb.updateMachineTool
是httpClient帖子,用于更新特定工具
this.sb.updateMachineTool
is an httpClient post that updates a specific tool
我应该使用某种类型的地图,以便我不同时订阅这两个区域吗?
should I be using some type of map so i'm not subscribing to both areas?
如何重构此代码?
推荐答案
To Refactor your code You can use
mergeMap
switchMap
您的问题是switchMap
的完美用例.因为您已经提到this.ds.onSave$
是一个主题,当单击另一个组件上的保存按钮时会触发该主题.
在这种情况下switchMap
给您带来的好处是,如果反复单击该按钮,它将自动取消所有旧的订阅(在您的情况下为Http Call in Progress).
your question is the perfect use case for switchMap
. because as you have mentioned this.ds.onSave$
is a subject that triggers when a save button on a different component is clicked.
The advantage switchMap
gives you in this scenario is it will cancel all the old subscription(Http Call in Progress in your case) automatically if the button is clicked repeatedly.
ModifiedCode
this.saveSubscription$ = this.ds.onSave$.pipe(switchMap(()=>
this.sb.updateMachineTool(this.viewEditModel.viewEditModel)
)
).subscribe(x = {
console.log('alert results', x)
});
了解更多
-
Understanding mergeMap and switchMap in RxJS
-
The Simple Difference Between RxJS switchMap and mergeMap
Understanding mergeMap and switchMap in RxJS
The Simple Difference Between RxJS switchMap and mergeMap
这篇关于如何在rxjs中的订阅中重构订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!