Angular 2 - 链接 http 请求

IT技术 javascript http angular rxjs
2021-02-28 11:11:48

我从 httpService 获得了一个 RxJS Observable,它是来自 Angular 的实际 http。现在,只要我从中得到一个积极的结果,我就想处理我从this.retrieve(). 这或多或少是串联请求。有更好的方法吗?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});
1个回答

可以使用flatMapswitchMap操作符链接 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);
    });
如何组合所有请求的返回并将其作为结果返回?
2021-04-21 11:11:48
太精彩了。非常感谢你!
2021-04-26 11:11:48
从 'rxjs/operators' 导入 {switchMap, flatMap};
2021-05-03 11:11:48
另请参阅switchMap()- switchMap -学习- rxjs
2021-05-04 11:11:48
你从哪里导入 flatMap?
2021-05-08 11:11:48