我有几个嵌套订阅。处理大规模缩进的任何好方法?

时间:2016-11-30 15:13:48

标签: angular rxjs

在我的某个组件的设置中,我需要进行多次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是否支持更好的方式?

1 个答案:

答案 0 :(得分:4)

您可以使用flatMap简化:

client
    .makeCall1()
    .flatMap(response1 => client.makeCall2(response1.prop))
    .flatMap(response2 => client.makeCall3(response2.prop))
    .flatMap(response3 => client.makeCall4(response3.prop))
    .subscribe(...);
相关问题