可以使用flatMap
或switchMap
操作符链接 HTTP 请求。假设我们要发出三个请求,其中每个请求都取决于前一个请求的结果:
this.service.firstMethod()
.flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
.flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
.subscribe(thirdMethodResult => {
console.log(thirdMethodResult);
});
通过这种方式,您可以链接尽可能多的相互依赖的请求。
更新:
从 RxJS 5.5 版开始,引入了可管道操作符,语法略有变化:
import {switchMap, flatMap} from 'rxjs/operators';
this.service
.firstMethod()
.pipe(
switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
)
.subscribe(thirdMethodResult => {
console.log(thirdMethodResult);
});