Search code examples
angularjsangular-resource

Using $resource to POST with a body


How do I do a normal POST with a payload body with Angular $resource. Right now, when I POST, it posts to /api/example?name=JoeSmith&is_whatever=false, instead of posting with a body.

Let's say I have the following:

ENDPOINT: `/api/example`
BODY: {
   "name": "Joe Smith",
   "is_whatever": false
}

API Service

angular.module('example')
   .factory('APIService', ['$resource',

        function($resource) {

           return $resource('/api/example', {}, {
              create: {
                 method: 'POST',
              }
           });          

        }]);

Example usage

    // body i need to POST
    var payload = {
       name: 'Joe Smith',
       is_whatever: false        
    };

    APIService.create(payload).$promise.then(function(res){
        // doesnt work
    });

Solution

  • Try passing the data parameter to the action method of the resource as follows:

    angular.module('example', ['ngResource'])
    
    .run(function(APIService) {
       var payload = {
          name: 'Joe Smith',
          is_whatever: false        
       };
       APIService.save({}, payload)
    })
    
    .factory('APIService', function($resource) {
       return $resource('/api/example');
    });