![](/img/trans.png)
[英]RxJs: Combine two Observables - Take all from first but not all from second
[英]RxJs: Executing 3 observables one after another and using results from first in second, and first and second in third requests
我需要能够一个接一个地执行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
分配适当的类型。
设法这样解决:
private checkFilePresence(): void {
const first$: Observable<string> = this.initRouteParams();
const second$: Observable<string> = first$.pipe(
switchMap(config => {
return this.getFileInfo(config);
})
);
const third$: Observable<CkitExistingFileResponse> = combineLatest(first$, second$).pipe(
switchMap(([config, second]) => {
return this.getExistingFile(config, second);
})
);
combineLatest(first$, third$)
.subscribe(() => {
});
}
您可以按以下顺序订阅可观察对象:
private setupStuff(): void {
this.initRouteParams().subscribe( serviceId => {
this.getFileInfo(serviceId).subscribe(fileName => {
this.getExistingFile(serviceId, fileName).subscribe( response => {
console.log(response);
});
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.