如何正确链接rxjs 6观测值?

时间:2018-10-12 07:17:16

标签: angular rxjs observable rxjs6

任何建议,如何以更多的承诺链方式重写它?:

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
        map(() => {
            return this.apiService.sendGetRequest('/api/users/' + this.currentUserId).pipe(
                map(data => {
                    return this.setActiveUser(data).pipe(
                        map(() => {
                            return this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId).pipe(
                                map(tasks => {
                                    return this.taskService.setCurrentUserTasks(tasks);
                                })
                            );
                        })
                    );
                })
            );
        })
    );

3 个答案:

答案 0 :(得分:2)

为此使用SwitchMap

mainApiCall.pipe(
    switchMap(result=>secondApiCall(result)),
    switchMap(resultFromSecondApiCall=>thirdApiCall(resultFromSecond))
...
and so on
)

答案 1 :(得分:2)

您可以使用switchMap来处理可观察对象,并使用tap来进行副作用处理。而且您需要订阅,因为它是cold observable

要进行错误处理,请对所有请求使用catchError

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
    catchError(err=> this.errorHandler(err)),
    switchMap(() => this.apiService.sendGetRequest('/api/users/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(data => this.setActiveUser(data)),
    switchMap(() => this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(tasks => this.taskService.setCurrentUserTasks(tasks))
).subscribe()

答案 2 :(得分:1)

为您的问题使用一个pipe。只需用逗号分隔不同的可链接运算符,例如mapswitchMapmergeMaptap等。

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
  switchMap((results) => this.apiService.sendGetRequest('/api/users/' + this.currentUserId)),
  tap((results) => this.setActiveUser(data)),
  switchMap(() => this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId)),
  tap((results) => this.taskService.setCurrentUserTasks(tasks))
);

简化:如果只想转换一个值而没有任何异步api调用,然后将其传递给另一个运算符或订阅,请使用map;如果只想在它们之间捕获值而不进行转换,请使用tap (例如用于记录)。还有switchMap用于调度其他api调用。

相关问题