我从 httpService 获取 RxJS Observable,这是来自 Angular 的实际 http。现在,一旦我得到积极的结果,我想处理我得到的下一个 http 请求this.retrieve()
。这或多或少是串联请求。有更好的方法吗?
return this.httpService.query(data)
.map(data => {
if(data.status > 1)
this.retrieve().subscribe();
return data;
});
链接 HTTP 请求可以使用flatMap
or switchMap
运营商。假设我们要发出三个请求,其中每个请求都取决于前一个请求的结果:
this.service.firstMethod()
.flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
.flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
.subscribe(thirdMethodResult => {
console.log(thirdMethodResult);
});
通过这种方式,您可以链接任意数量的相互依赖的请求。
UPDATE:从 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);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)