使用angularJS中的$ resource将ID发送到DELETE API

时间:2018-07-19 10:49:40

标签: angularjs ngresource

对于我的angularJS服务,我有$ resource的delete方法,

#

但是,在尝试调用delete方法时,从服务发送的请求中没有itemId。

return $resource(apiUrl, {}, {
    delete: {
        url: apiUrl+ ":itemId",
        params: { itemId: "@itemId" },
        method: 'DELETE'
    }
});

应该调用的URL为https://url:someport/v1.0/items/ {itemId} 但是,当前网址是https://url:someport/v1.0/items

是否有一种方法可以使用当前的$ resource代码获取此能源部?

2 个答案:

答案 0 :(得分:1)

code发送正确的网址:

angular.module("app",['ngResource'])
.controller("ctrl",function($scope,$resource){
  var url = "//requestbin.fullcontact.com/1ooe8eb1";
  var dataService =  $resource(url, {itemId: "@itemId"}, {
    delete: {
        url: url+"/items/:itemId",
        params: { itemId: "@itemId" },
        method: 'DELETE'
    }
  });
  $scope.delete = function() {
    var res = dataService.delete({itemId:77});
    res.$promise.finally(function(){
      $scope.result="DONE";
    });
  };
});
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-resource/angular-resource.js"></script>
<body ng-app="app" ng-controller="ctrl">
    <button ng-click="delete()">Delete Item</button>
    {{result}}
</body>

由于CORS,浏览器阻止了响应,但在以下位置进行了检查:

https://requestbin.fullcontact.com/1ooe8eb1?inspect

表明网址格式正确。

答案 1 :(得分:0)

我认为您需要使用第二个参数为请求指定参数。

return $resource(apiUrl, {itemId: '@itemId'}, {
delete: {
    method: 'DELETE'
}
});

您可以在https://docs.angularjs.org/api/ngResource/service/$resource上查看整个文档。这会给你更好的主意。您需要在第二个参数(对象)中提供参数。

var User = $resource('/user/:userId',
{userId: '@id'},
{delete: {
    method: 'DELETE' }
});

User.delete({userId: 123}).$promise.then(function(user) {
  // perform other operations
});