Angular 2 - Chaining http requests

2019-01-07 23:25发布

问题:

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;
});

回答1:

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.