[英]How to properly chain rxjs 6 observables?
Any suggestions, how this can be rewritten in more promise-chaining style?: 有什么建议,如何用更多的承诺链式改写?:
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);
})
);
})
);
})
);
})
);
use SwitchMap
for that. 使用
SwitchMap
。
mainApiCall.pipe(
switchMap(result=>secondApiCall(result)),
switchMap(resultFromSecondApiCall=>thirdApiCall(resultFromSecond))
...
and so on
)
You can use switchMap for handling observables and tap for side efects handling. 您可以使用switchMap处理可观察对象并点击侧面效果处理。 And you need to subscribe because it's cold observable
你需要订阅因为它是冷的可观察的
For error handling use catchError for all requests 对于错误处理, 请对所有请求使用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()
Use a single pipe
for your problem. 使用单个
pipe
解决您的问题。 Just comma seperate different chainable operators like map
, switchMap
, mergeMap
, tap
, etc. 只需逗号分隔不同的可链接运算符,如
map
, switchMap
, mergeMap
, tap
等。
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))
);
Simplified: Use map
if you just want to transform a value without any async api calls and pass it to another operator or a subscription, tap
if you just want to catch values in between without transforming (eg for logging). 简化:使用
map
,如果你只是想没有任何异步API调用来转换一个值,并将其传递到另一个运营商或订阅, tap
,如果你只是想赶上两者之间的值,而不转化(如日志记录)。 And switchMap
for dispatching additional api calls. 并且
switchMap
用于调度其他api调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.