AngularJS $resource DELETE item in collection

陌路散爱 提交于 2019-12-11 14:24:19

问题


I have an ASP.NET Web Api (1) controller with GET, POST and DELETE actions. I am calling this from an Angular 1.2.0 RC3 app with $resource. Let's call the controller Foos.

I do a GET that returns a list of foos:

GET http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6

where the resource is

/api/foos/clientId/recordId

Here I am saying get me a list of foos for client x and record y

Now, I want to remove a single foo from the list of foos that I received, so I call $delete:

$scope.delete = function(foo){
    foo.$delete();
}

however this results in the following request:

DELETE http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6

This delete is obviously trying to delete the entire list of foos, which makes sence.

My question is, how do I delete a single foo using Angular's $resource without getting each foo in its own GET request?

UPDATE:

I could do a GET /api/foo/1 where the resource is foo/fooId, and its equivalent DELETE /api/foo/1 to delete it but I want to get a list of foos instead of each foo individually.


回答1:


I know that is not the question but you should restangular https://github.com/mgonto/restangular. It is easier to interact with rest services




回答2:


I was misunderstanding how $resource works. I assumed thatfoo knew how to delete itself as it is a Resource 'instance' in the following function:

$scope.delete = function(foo){
    foo.$delete();
}

The correct approach is:

$scope.delete = function(foo){
    Api.delete({ 
        id: foo.Id, 
        clientId : $scope.clientId, 
        recordId : $scope.recordId 
    });
}

You have to manually tell the $resource instance to use the id of foo so that the url includes the foo id and does the following DELETE

DELETE http://localhost:55386/api/foos/123456/1/123 HTTP/1.1

where 123 is fooId



来源:https://stackoverflow.com/questions/26733076/angularjs-resource-delete-item-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!