I am trying to send data in the body of a POST request to a RESTful API in my AngularJS application.
My current structure for this request is a controller which grabs data and send this to a service, which then calls the request from its associated factory, as follows:
Controller
userService.saveReport(vm.user.id, searchParams)
Service
service.saveReport = function (id, searchData) {
var deferred = $q.defer();
user.saveReport({ userID: id, searchData: searchData }, function(response) {
deferred.resolve(response);
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
Factory
function user($resource, $localStorage, constants) {
return $resource(constants.API_URL + '/users', { userID: '@userID' }, {
getReports: {
method: 'GET',
url: constants.API_URL + '/users/:userID/reports',
format: 'json',
headers: {
'Accept': 'application/vnd.abp.v1+json',
'X-Mode': function() {
return $localStorage.get('mode');
}
}
},
saveReport: {
method: 'POST',
url: constants.API_URL + '/users/:userID/reports',
format: 'json',
headers: {
'Accept': 'application/vnd.abp.v1+json',
'X-Mode': function() {
return $localStorage.get('mode');
}
}
}
});
}
angular
.module('abp')
.factory('user', user);
})();
I have seen various posts which state $resource allows data: to be send through to form the body of the request, but this doesn't seem to be working. I've tried to add searchData: '@searchData' into the params allowed by the $resource call and then add this into a data section as follows, but this doesn't work (condensed for brevity):
return $resource(constants.API_URL + '/users', { userID: '@userID', searchData: '@searchData' }, {
saveReport: {
method: 'POST',
url: constants.API_URL + '/users/:userID/reports',
format: 'json',
data: ':searchData',
headers: {
'Accept': 'application/vnd.abp.v1+json',
'X-Mode': function() {
return $localStorage.get('mode');
}
}
}
}
How can I send the data of this request in the body of the POST request?