AngularJS $resource DELETE item in collection

2019-09-04 10:23发布

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.

2条回答
Root(大扎)
2楼-- · 2019-09-04 10:37

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

查看更多
乱世女痞
3楼-- · 2019-09-04 10:59

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

查看更多
登录 后发表回答