问题
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.
Something like this (it doesn't work as the serviceId is not visible in the third request):
private setupStuff(): void {
this.initRouteParams().pipe(
switchMap(serviceId => this.getFileInfo(serviceId)),
switchMap(fileName => this.getExistingFile(serviceId, fileName)
.subscribe(response => {
console.log(response);
}))
);
}
回答1:
You can explicitly return the value of the serviceN to the 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
.
回答2:
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(() => {
});
}
回答3:
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);
});
});
});
}
来源:https://stackoverflow.com/questions/51601510/rxjs-executing-3-observables-one-after-another-and-using-results-from-first-in