Reputation: 23372
I thought this would be simple to do but it terribly confusing.
I want to set my Angular login form to allow my users to login. On the login form, I want to take the input and send it as a POST
request to my server for verification.
However, I cannot find a single example of $resource
being used to send a POST
request. Does anyone have any examples they can share?
Upvotes: 3
Views: 3686
Reputation: 7920
After defining your resource, you can use the save method which is default action for post defined by $resource
. The first parameter of save takes arguments used as url params, and the second parameter takes post data.
var LoginResource = $resource("/rest/path/login");
var bodyObject = {username:"test", password:"test"};
LoginResource.save({}, bodyObject);
Then you can access response to your request by using promise of $resource
. To clarify I will give an sample service and controller which will make a post request.
angular.module('yourApp').
factory('yourService', ["$resource", function($resource){
var LoginResource = $resource("/rest/path/login");
var serviceObject = {loginUser: function (userName, password){
return LoginResource.save({}, {userName: userName, password: password}).$promise; //this promise will be fulfilled when the response is retrieved for this call
}};
return serviceObject;
}];
angular.module("yourApp").controller("LoginCtrl", ["$scope", "yourService",
function($scope, yourService){
yourService.loginUser("test", "test").then(
function(loginResult){
console.log(loginResult);
},
function(err){
console.error(err);
}
)
}];
Upvotes: 6
Reputation: 14417
If you look on the docs: https://docs.angularjs.org/api/ngResource/service/$resource
Scroll down to where you can see Returns.
You will see this list:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
This is where it tells you what is defined on the $resource
object by default. As you can see if you call get
then you will use HTTP GET
, save
=> HTTP POST
.
So if you define this:
var User = $resource('/user/:userId', {userId:'@id'});
Then you can perform a GET
:
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
If you define this:
var User = $resource('/user/:userId', {userId:'@id'}, {specialAction: {method: 'POST'}});
And call it:
User.specialAction({someParam:someValue});
You will perform the same action as save
. You have just renamed it :)
So $resource
just wraps around $http
to make using RESTful API's easier. You can defined your own set of methods if you wish, you can specify to great detail how these are supposed to be executed.
Upvotes: 1