如何使用Angular的$ resource发送登录POST请求?

时间:2014-12-08 14:24:19

标签: angularjs http ngresource

我认为这样做很简单,但非常令人困惑。

我想设置我的Angular登录表单以允许我的用户登录。在登录表单上,我想接收输入并将其作为POST请求发送到我的服务器进行验证。

但是,我找不到用于发送$resource请求的POST的单个示例。有没有人有他们可以分享的任何例子?

2 个答案:

答案 0 :(得分:6)

定义资源后,您可以使用保存方法,该方法是$resource定义的帖子的默认操作。 save的第一个参数接受用作url params的参数,第二个参数接受post数据。

var LoginResource = $resource("/rest/path/login");
var bodyObject = {username:"test", password:"test"};
LoginResource.save({}, bodyObject);

然后,您可以使用$resource的承诺访问对您的请求的回复。为了澄清我将提供一个样本服务和控制器,它将发布一个帖子请求。

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);
        }
    )
  }];

答案 1 :(得分:1)

如果您查看文档:{​​{3}}

向下滚动到您可以看到返回的位置。

您将看到此列表:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

默认情况下,它会告诉您$resource对象上定义的内容。如您所知,如果您拨打get,则会使用HTTP GETsave => HTTP POST

所以如果你定义这个:

var User = $resource('/user/:userId', {userId:'@id'});

然后你可以执行GET

var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

如果你定义:

var User = $resource('/user/:userId', {userId:'@id'}, {specialAction: {method: 'POST'}});

并称之为:

User.specialAction({someParam:someValue});

您将执行与save相同的操作。你刚刚重命名了它:)

因此,$resource只需绕过$http,以便更轻松地使用RESTful API。如果愿意,您可以定义自己的一组方法,您可以详细说明如何执行这些方法。