Angular 2 - 链接http请求

Tre*_*tor 15 javascript http rxjs angular

我从一个httpService获得一个RxJS Observable,这是来自Angular的实际http.现在,一旦我从中获得了积极的结果,我想处理我得到的下一个http请求this.retrieve().这或多或少是连续请求.有没有更好的方法呢?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});
Run Code Online (Sandbox Code Playgroud)

Sei*_*vic 21

可以使用Observable.flatMap运算符实现链接HTTP请求.假设我们想要发出三个请求,其中每个请求取决于前一个请求的结果:

this.service.firstMethod()
    .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
    .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
    .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
     });
Run Code Online (Sandbox Code Playgroud)

这样,您可以链接所需的相互依赖的请求.

  • 那太好了。非常感谢你! (2认同)