本文介绍了Angular 2 - 链接http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get a RxJS Observable from an httpService which is the actual http from Angular. Now as soon as I get a postive result from that, I want to process the next http Request which I get from this.retrieve(). This is more or less concattening requests. Is there a better way of doing it?

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


推荐答案

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

Chaining HTTP requests can be achieved using the Observable.flatMap operator. Say we want to make three requests where each request depends on the result of previous one:

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

通过这种方式,您可以链接所需的相互依赖的请求。

This way you can chain as much interdependent requests you want.

这篇关于Angular 2 - 链接http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:04