在我的某个组件的设置中,我需要进行多次Web服务调用。我有这样的事情:
client.getUserProject()
.subscribe(
(usersProject) => {
this.mainProject= usersProject.mainProject;
client.getRelatedProjects(usersProject.keyWords)
.subscribe(
(relatedProjects) => {
this.sanitizeProjects(relatedProjects.projects);
client.loadAdditionalAssets(relatedProjects.dependencies)
.subscribe(
(response3) => {
client.makeCall4(response3.prop)
...
},
(err) => {
// do something different than the other onErrors
}
)
},
(err) => {
// display warning about related projects not being ready and set some flags
}
)
},
(err) => {
// display an error and prompt the user to reload the page
}
)
当我深入几层时,缩进变得有点疯狂。我需要进行所有这些调用,但我想知道是否有更好/不同的方式来构建它。事情最终缩小到线条必须超过140标记的点,这是我们的指南/ lint指定的。
Angular / RXJS是否支持更好的方式?
答案 0 :(得分:4)
您可以使用flatMap
简化:
client
.makeCall1()
.flatMap(response1 => client.makeCall2(response1.prop))
.flatMap(response2 => client.makeCall3(response2.prop))
.flatMap(response3 => client.makeCall4(response3.prop))
.subscribe(...);