我想在单个流中链接多个可观察量,并在管道链中进一步保留先前的值。
每个可观察量必须按顺序运行(一个接着一个,例如:如果第一个可观察量完成,则必须转到下一个)并且顺序很重要。我不想并行订阅它们(就像forkJoin一样)
输出必须向我提供用户信息、手机、地址和电子邮件。
我可以用switchmap来做到这一点,这种方法确实有效;但有更好的方法吗?
只是一个虚拟示例:
this.userService.getUser(id)
.pipe(
switchMap(userResponse => {
return this.cellphoneService.getCellphones(userResponse.id)
.pipe(
map(cellphonesResponse => [userResponse, cellphonesResponse])
)
}),
switchMap(([userResponse, cellphonesResponse]) => {
return this.emailService.getEmails(userResponse.id)
.pipe(
map(emailResponse => [userResponse, cellphonesResponse, emailResponse])
)
}),
switchMap(([userResponse, cellphonesResponse, emailResponse]) => {
return this.addressService.getAddresses(userResponse.id)
.pipe(
map(addressResponse => [userResponse, cellphonesResponse, emailResponse, addressResponse])
)
}),
).subscribe(response => console.log(response))
Run Code Online (Sandbox Code Playgroud)
您可以嵌套 switchMap,而不是在每次调用后将响应映射到数组,然后所有响应都将在范围内,因此您可以只使用单个映射:
this.userService.getUser(id).pipe(
switchMap(user => this.cellphoneService.getCellphones(user.id).pipe(
switchMap(cellphones => this.emailService.getEmails(user.id).pipe(
switchMap(email => this.addressService.getAddresses(user.id).pipe(
map(address => [user, cellphones, email, address])
))
))
))
).subscribe(response => console.log(response))
Run Code Online (Sandbox Code Playgroud)
这个答案对此进行了更详细的描述
| 归档时间: |
|
| 查看次数: |
4878 次 |
| 最近记录: |