1

I am iterating over an array (using forEach method) and calling DELETE http method in Angular

array: ["1", "2", "3"];

url: [DELETE] http://localhost/deleteUser/{{id}}

code:

    users.forEach(user => {
      this.http.delete(`http://localhost/deleteUsers/${user}`).toPromise());
    });

I am getting 422 unprocessable error

Error Message: The entity "claim Primary Key> 56,156" cannot be updated because it has changed or been deleted since it was last read. This error happens only when I do it from Angular. I tried with scripts and postman and it was working fine.

But, when I try the same from postman collection runner looping over the list, it works fine without any error.

From Angular I tried adding some delays after every request and still getting the same error. This is error occurs randomly and only for some of the requests in the array (no specific request it is just random).

Postman collection below (works fine)

enter image description here

Dot Net Dev
  • 574
  • 8
  • 20
  • what error are you getting in angular? – Andrei Sep 22 '20 at 18:47
  • @Andrei, "The entity "claim Primary Key> 56,156" cannot be updated because it has changed or been deleted since it was last read", I don't have access to backend so I could not debug the issue. – Dot Net Dev Sep 22 '20 at 18:50
  • Is it possible your array contains duplicates or at least items with a duplicate id..? – MikeOne Sep 22 '20 at 18:55
  • @MikeOne no, they are primary keys and are unique – Dot Net Dev Sep 22 '20 at 19:01
  • Please check this post [https://stackoverflow.com/questions/50892416/how-to-make-a-massive-delete-in-angular-4-with-an-array-of-ids](https://stackoverflow.com/questions/50892416/how-to-make-a-massive-delete-in-angular-4-with-an-array-of-ids) Hope this will help! – Amit Aggrawal Sep 22 '20 at 21:13

1 Answers1

0

Please check this post https://stackoverflow.com/questions/50892416/how-to-make-a-massive-delete-in-angular-4-with-an-array-of-ids

Instead of executing a for loop for each ID, you can send all the IDs at once in the body. Do check the comments there if you want to know how to retrieve IDs on server side from request body.

Note: That answer is valid if your angular version is 2.x, 4.x or 5.x. If your angular version is 6.x or above then try this

const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
  body: {
    id: 1,
    name: 'test',
  },
};

this.httpClient
  .delete('http://localhost:8080/something', options)
  .subscribe((s) => {
    console.log(s);
  });

For more information check https://angular.io/api/common/http/HttpClient#delete

Amit Aggrawal
  • 59
  • 1
  • 10