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;
});
You could use RxJS forkJoin along with Array#map to trigger multiple observables in parallel.
forkJoin is an operator that takes any number of input observables which can be passed either as an array or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed), then the resulting stream will complete immediately.
Chaining 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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With