Angular.js delete resource with parameter

后端 未结 4 1659
醉酒成梦
醉酒成梦 2021-02-01 17:52

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 de

相关标签:
4条回答
  • 2021-02-01 17:52

    Just omit the '@' in the parameter

       .factory('reportFactory', ['$resource', 'baseUrl', function ($resource, baseUrl) {
            return $resource(baseUrl + '/keys/:id', {}, {
            delete: { method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                params: {id: 'id'} }
           })
    }]);
    

    this will give you:

      http://localhost:8080/reports/api/keys/b8a8a8e39a8f55da94fdbe6c 
    

    without the question mark

    0 讨论(0)
  • 2021-02-01 17:54

    I had this problem for a while I was using a service to add / delete / update categories. While passing in params for get it worked fine but then when deleting it was giving me a ?id=1234 instead of api/resource/1234

    I got around this by making the default param a string.

    ///Controller

    Service.delete({categoryId:id}, function(resp){
      console.log(resp)//whatever logic you want in here 
    });
    

    //SERVICES

    $resource('api/resource/:categoryId', {"categoryId":"@categoryId"}, {
       query:{method:"GET"},
       delete:{method:"DELETE"},
    
    });
    

    Should work and the resulting url will be, originally I had categoryId in the default params as a variable name.

    api/resource/1234 etc
    
    0 讨论(0)
  • 2021-02-01 17:54

    If you want to delete a model, there's no need to add params (params does not work for DELETE anyway):

    $resource('/users/:id').delete({id: user.id}, function(res) {
      ...
    })
    

    or

    $resource('/users/:role/:id').delete({role: 'visitor', id: user.id});
    

    I'm not sure if it's a bug of ngResource.

    0 讨论(0)
  • 2021-02-01 18:14

    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.

    0 讨论(0)
提交回复
热议问题