Reputation: 825
I'm trying to figure out how to pass data to an API through Angular's $resource
. I can GET
or query any data from my test server currently, but I also want to see how to POST
new data to the server. I am using this code that I've adapted from the AngularJS docs:
.factory("ResourceTest", function($resource) {
return $resource("http://mywebsite.com/api/:id", {id:'1'}, {
charge: {method:'POST', params:{charge:true}}
});
});
When I run ResourceTest.charge();
in my controller, it works fine, and I see a POST
request in my server logs. But when I try to pass any parameters when I call the function (eg ResourceTest.charge({test:false});
), the request will not go through, and I can't see any request in the logs. (same happens with .save()
, in case anyone is wondering)
Anyone know if it's just a code error I'm making here? I'm pretty new to AngularJS. Thanks!
Upvotes: 2
Views: 1741
Reputation: 825
Finally figured it out. The request headers needed to be changed, apparently. Here's the code I added to make it work, hope it helps someone else out.
.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
})
Upvotes: 1
Reputation: 1563
What did you expect the $resource object to do?
If you pass in a data object to the $resource charge function it will send the data as the request payload to the url you defined. See working example below.
myApp.factory("ResourceTest", function($resource) {
return $resource("http://mywebsite.com/api/:id", {id:'1'}, {
charge: {method:'POST', params:{charge:true}}
});
});
myApp.controller('MyCtrl', function($scope, ResourceTest) {
$scope.name = 'Superhero';
$scope.test = function (userInput) {
console.log("check the browser console Network > XHR to see the request payload");
ResourceTest.charge({'userInput':userInput});
}
});
Upvotes: 0
Reputation: 6221
It appears that you are pulling from the angular docs to try and get resource up and running. I had quite a time myself and didn't find the docs to very helpful in understanding ngResource and how to correctly implement it.
This article clears things up quite a bit:
http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/
Upvotes: 1