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);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…