Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending id to DELETE API using $resource in angularJS

I have this delete method with $resource for my angularJS service,

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

However while trying to call the delete method, the request which sends from the service is without itemId.

dataService.delete({ itemId: itemId}, {})
                .$promise
                .then((data) => {
                    // Statements
                })
                .catch((error) => {
                    // Logging
                })
                .finally(() => {});

The URL supposed to call is https://url:someport/v1.0/items/{itemId} However the current url is https://url:someport/v1.0/items

Is there a way to get this doe using the current $resource code?

like image 793
TBA Avatar asked Jul 19 '18 10:07

TBA


1 Answers

This code sends the proper url:

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>

The response is blocked by the browser because of CORS but inspection at:

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

shows that the URL was formed correctly.

like image 130
georgeawg Avatar answered Oct 06 '22 08:10

georgeawg