I need to execute two requests consecutively and merge their results at the end.
- If the response body of the first request contains
isSuccessful = false
, then the second request should not be executed. - If the first request fails for any reason, the second request should not proceed.
- If the second request fails, it should not affect the outcome of the first request. The function
combineAndPrintMsg()
should still work with just the message from the first request.
I attempted nesting subscriptions in the code snippet below, but I've been advised that this is not the best approach.
firstReq = this.http.get("https://myApi.com/posts?userId=1");
secondReq = this.http.get("https://myApi.com/albums?userId=1");
.....
this.firstReq.subscribe(res1 => {
const secondReqResult = this.doSecondRequest(res1);
this.combineAndPrintMsg(res1, secondReqResult)
})
.....
doSecondRequest(res1: any) {
let secondReqResponse;
if (res1.isSuccessful) {
this.secondReq.subscribe(res2 => {
secondReqResponse = res2;
})
return secondReqResponse;
}
}
combineAndPrintMsg(res1, res2) {
console.log(res1.message + res2.message || '');
}