Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js delete resource with parameter

Tags:

My rest api accpets DELETE requests to the following url

/api/users/{slug} 

So by sending delete to a specified user (slug) the user would be deleted. here is the service code:

angular.module('UserService',['ngResource']).factory('User', function($resource){     var User = $resource('/api/users/:id1/:action/:id2', //add param to the url     {},      {          delete_user: {             method: 'DELETE',             params: {                 id1:"@id"             }         },         update: {             method: 'PUT',             params: {                 id1:"@id"             }         }     });       return User; });  

I call the delete function via

user.$delete_user({id:user.id}, function(){}, function(response){});  

However the request seems to be send to the wrong url.

/api/users?id=4 

So the parameter is actually missing, as a result I get a 405 Method not allowed. Is there any chance to send the delete request in the style of my api?

like image 809
UpCat Avatar asked Apr 23 '13 10:04

UpCat


Video Answer


1 Answers

params is an object of default request parameteres in your actions. If you want url parameters you have to specify them in the second parameter like this:

angular.module('UserService',['ngResource']).factory('User', function($resource){     var User = $resource('/api/users/:id1/:action/:id2', //add param to the url     {id1:'@id'},     {          delete_user: {             method: 'DELETE'         }     });       return User; });  

this works with either:

// user has id user.$delete_user(function(){   //success },function(){   // error }); 

or

var data = {id:'id_from_data'}; User.delete_user({},data); 

or

var params = {id1:'id1_from_params'}; User.delete_user(params); 

I've made a plnkr-example - you have to open your console to verify that the DELETE requests are correct.

See parameterDefaults in the Angular resource documentation.

like image 108
joakimbl Avatar answered Dec 19 '22 13:12

joakimbl