我需要能够一个接一个地执行 3 个可观察对象,以便我可以在第二个中使用第一个的结果值,在第三个中使用第一个和第二个结果。
类似这样的事情(它不起作用,因为 serviceId 在第三个请求中不可见):
private setupStuff(): void {
this.initRouteParams().pipe(
switchMap(serviceId => this.getFileInfo(serviceId)),
switchMap(fileName => this.getExistingFile(serviceId, fileName)
.subscribe(response => {
console.log(response);
}))
);
}
最佳答案
您可以显式地将 serviceN 的值返回给 serviceN+1。这是想法:
private setupStuff() {
this.initRouteParams()
.pipe(
switchMap(serviceId => {
return zip(of(serviceId), this.getFileInfo(serviceId))
}),
switchMap(([serviceId, filename]) => {
return zip(of(serviceId), of(filename), this.getExistingFile(serviceId, filename))
})
)
.subscribe(([serviceId, filename, response]) => {
console.log(serviceId, filename, response);
})
}
编辑:
您可以通过显式声明每个输入的类型来修复类型错误。您可能想为 response
分配适当的类型。
关于javascript - RxJs:依次执行 3 个可观察对象,并在第二个请求中使用第一个,在第三个请求中使用第一个和第二个的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601510/