'Sending Multiple Post Request in Parallel on Angular
I have to Send Multiple Post request with same URL but different payload and to check status of each request, if its failed or success. and then i want to check data variable with all recored like 1 failed 2 success , with below code its not working
let id = [123,345,456];
let data = [];
id.foreach(payload=>{
let keyResponse = [{
status: ""
}];
this.restService.post('test/api',payload).subscribe(
(output: any) => {
keyResponse[0].status = "SUCCESS" ;
data.push(keyResponse[0]);
},
err => {
keyResponse[0].status = "ERROR" ;
data.push(keyResponse[0]);
}
);
});
console.log(data);
Solution 1:[1]
Since you're dealing with RXJS, you can use its forkJoin
operator.
First, make a list of HTTP request observables. Make sure to tell Angular to observe the response to capture the response status later for processing.
const ids = [123, 345, 456];
const requests = ids.map((id) => this.restService.post('test/api', id, { observe: 'response' }));
With the list of observables, pass it to forkJoin
so that upon subscription, those HTTP requests will trigger in "parallel," and will aggregate all responses. Only then we can finally be able to count the number of successful and failed requests.
forkJoin(requests).subscribe((responses) => {
let successCount = 0;
let failedCount = 0;
responses.forEach((response) => {
if(response.ok) {
++successCount;
}
else {
++failedCount;
}
});
console.log(successCount, 'successful requets.');
console.log(failedCount, 'failed requets.');
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |