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;
});
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;
});
Share
Improve this question
edited Mar 6, 2017 at 14:50
seidme
13k5 gold badges38 silver badges41 bronze badges
asked Mar 6, 2017 at 13:11
Trevor HectorTrevor Hector
6391 gold badge7 silver badges19 bronze badges
1 Answer
Reset to default 23Chaining HTTP requests can be done using flatMap
or switchMap
operators. 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.
UPDATE: As of RxJS version 5.5 pipeable operators were introduced and the syntax has slightly changed:
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);
});