[英]RxJs: Executing 3 observables one after another and using results from first in second, and first and second in third requests
I need to be able to execute 3 observables one after another so that I can use result value from 1st one in second and also 1st and 2nd result in the third one. 我需要能够一个接一个地执行3个可观察变量,以便可以在第二个中使用第一个结果,在第三个中使用第一个和第二个结果。
Something like this ( it doesn't work as the serviceId is not visible in the third request ): 这样的事情( 由于serviceId在第三个请求中不可见,因此不起作用 ):
private setupStuff(): void {
this.initRouteParams().pipe(
switchMap(serviceId => this.getFileInfo(serviceId)),
switchMap(fileName => this.getExistingFile(serviceId, fileName)
.subscribe(response => {
console.log(response);
}))
);
}
You can explicitly return the value of the serviceN to the serviceN+1. 您可以将serviceN的值显式返回给serviceN + 1。 Here's the idea : 这是个主意:
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);
})
}
Edit: 编辑:
You can fix types errors by explicitly declare types of each input. 您可以通过显式声明每个输入的类型来修复类型错误。 You probably want to assign the appropriate type for response
. 您可能想为response
分配适当的类型。
managed to solve it like this: 设法这样解决:
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(() => {
});
}
You can subsribe to observables in sequence as below: 您可以按以下顺序订阅可观察对象:
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.