AngularJS and REST: perform DELETE action sending

2019-09-14 13:20发布

I'm in a confused trouble with AngularJS and my REST API (Java). I've created a tree-view-drag-drop directive, it has a function to select its items and then delete them, but when I perform a DELETE action using $resource, AngularJS overrides or ignores the request body that is where I send the items of my selection array, how can I solve it? Is there any other patterns that I can use? Maybe some modification in API... or I don't know I'd like some suggestions about this problem and how to solve in the best way both in backend and frontend.

UPDATE

JSFiddle: http://bit.ly/1QmG83Z

3条回答
太酷不给撩
2楼-- · 2019-09-14 13:41

Perhaps the best approach should be creating a POST request, where you would pass your array, and then you could treat the delete atomically:

Service

MyService.$inject = ['$resource'];
function MyService($resource) {
    return $resource('/echo/json', {}, {
        remove: {
           method: 'POST'
        }
});

Call

MyService.remove(categoriesToDelete, function(response) {
    console.log(response);
    // do something after deletion
}

REST method example

@POST
@Path("/json")
@Consumes(MediaType.APPLICATION_JSON)
public Response delete(final String array) {
    // You can convert your input to an array and then process it
    JSONArray responseArray = new JSONArray(array);

    System.out.println("Received input: " + responseArray);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("Array received", responseArray);

    return Response.status(Status.OK).entity(jsonObject.toString()).build();
}

Also, take a look at this post for further enlightenment.

查看更多
等我变得足够好
3楼-- · 2019-09-14 13:41

Well, all the ideas you gave me were great, and helped me to reach a solution, but reading all the answers and other topics the best solution that I found was to group all ID's in a single string separated by spaces, then I pushed to the path variable, and made a DELETE request as a single resource. Then, my endpoint will split the "combined-resource" and retrieve each of them separately to perform a delete action.

查看更多
别忘想泡老子
4楼-- · 2019-09-14 13:44

As far as I know, HTTP method DELETE doesn't take a body.

You would need an endpoint in your api to treat this "batch" request using an array in body

Or you could also launch a DELETE request on each resource via Angular without any body

查看更多
登录 后发表回答