How do you send a POST request for login using Angular $ resource?
I thought it would be easy to do, but it's terribly confusing.
I want to set up my Angular registration form so that my users can login. In the login form, I want to do some input and send it as a request POST
to my server for verification.
However, I cannot find one example $resource
that is used to send the request POST
. Does anyone have any examples they can share?
source to share
After defining your resource, you can use the save method, which is the default action for the message defined $resource
. The first parameter to save takes arguments used as url parameters, 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 get a response to your request using a promise $resource
. To clarify, I'll give a sample service and controller that will make the 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);
}
)
}];
source to share
If you look at the docs: https://docs.angularjs.org/api/ngResource/service/$resource
Scroll down to Refunds.
You will see this list:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
This specifies what is defined $resource
by the default object . 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 do 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 follow the same steps as save
. You just renamed it :)
So, $resource
just wraps around $http
to make it easier to use the RESTful API. You can define your own set of methods if you like, you can specify in detail how they should be executed.
source to share