如何使用$ resource向我的服务器发送HTTP DELETE请求?

时间:2013-09-04 18:14:03

标签: angularjs

我有以下代码:

var entityResource = $resource('/api/' + $scope.entityType + '/');

entityResource.delete(entityId,
   function (result) {
      $scope.remove($scope.grid.data, idColumn, entityId);
   }, function (result) {
      alert("Error: " + result);
   })

当代码执行时,我收到以下消息:

DELETE http://127.0.0.1:81/api/Subject 404 (Not Found) 

{"message":"No HTTP resource was found that matches the request URI 'http://127.0.0.1:81/api/Subject'.","messageDetail

我怎样才能让$资源发送带有/ api / Subject / 123的DELETE现在它似乎忽略了entityId的值

以下是我在建议之后尝试的内容:

    var entityResource = $resource('/api/:entityType/:entityId',
           { entityType: '@type', entityId: '@id' });
    entityResource.delete({ type: $scope.entityType, id: entityId }, 
        function (result) {
            $scope.remove($scope.grid.data, idColumn, entityId);
            $scope.remove($scope.grid.backup, idColumn, entityId);
            $scope.close();
        }, function (result) {
            alert("Error: " + result);
        })

不幸的是,这给了我:DELETE / api?id = 12& type = Subject HTTP / 1.1

1 个答案:

答案 0 :(得分:2)

您需要在模板中设置实体ID:

var entityResource = $resource('/api/:entityType/:entityId', 
                               {type:'@entityType', id: '@entityId'});

然后当你调用它时,传递参数:

entityResource.delete({type: $scope.entityType, id: entityId}, success, failure);

var entity = new entityResource({type: $scope.entityType, id: entityId});
entity.$delete(success, failure);

假设successfailure看起来像这样:

var success = function (result) {
    $scope.remove($scope.grid.data, idColumn, entityId);
};

var failure = function (result) {
    alert("Error: " + result);
};