0

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);
2
  • 1
    Doesn't the payload have to be an object? Commented May 6, 2022 at 5:44
  • For HttpClient.post, it does not have to be an object. You might be mistaking it for HttpClient.get, where payload needs to be an object, under the params option. Commented May 6, 2022 at 6:38

1 Answer 1

2

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.');
});
Sign up to request clarification or add additional context in comments.

4 Comments

it's unnecessary spread the response
in case of forkjoin,once any source failed,It will emit error to observer and will come out from pipe.And in OP it's mentioned i want to check data variable with all recored like 1 failed 2 success
@Eliseo you're right, it went over my head for some reason. Post updated, thanks!
@Saptarsi that's why I mentioned adding { observe: 'response' }. So that if any request fails, it won't signal an error and "come out from pipe." ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.