角度资源传递不需要的参数

时间:2014-04-26 22:39:05

标签: javascript ruby-on-rails angularjs angular-resource

我正在尝试使用这样的rails设置服务器端身份验证服务:

使用Javascript:

angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
    return $resource('/sessions',{}, {
      create: {method: 'POST', isArray: false},
      destroy: {method:'DELETE', url: '/sessions/destroy.json' }
    });
}])
.controller("LoginController",['$scope','Session',function($scope,Session){
  $scope.model = {};

  $scope.login = function(username,password){
    //Session.save({username: username, password: password}).then(function(success){
    //  $scope.model.user = success.data;
    //  console.log("New Session");
    //},function(error){
    //  console.log("Login failed!!!");
    //  console.log(error);
    //});
    $scope.model.user = {
      first: "John",
      last: 'Doe'
    };
  };

  $scope.logout = function(){
    Session.destroy().then(function(success){
      $scope.model.user = {};
      console.log("Session Deleted!!!");
    },function(error){
      console.log("Error in Session delete...");
      console.log(error);
    })
  };

}]);

HTML:

    <div class="navbar navbar-inverse" role="navigation" ng-controller="LoginController">
      <div class="navbar-right navbar-form " style="color:white" ng-show="model.user">
        <span class="glyphicon glyphicon-user"></span>
        <span>{{ model.user.first + ' ' + model.user.last}}</span>
        <button ng-click="logout()" type="submit" class="btn btn-danger navbar-btn">Logout</button>
      </div>
      <div class="navbar-form navbar-right" role="login" ng-hide="model.user">
        <div class="form-group">
          <a ng-href="#">new user? </a>
          <a ng-href="#"> forgot password?</a>
        </div>
        <form class="form-group" name="loginForm" ng-submit="login()">
          <input type="text" class="form-control" placeholder="username" ng-model="username" />
          <input type="password" class="form-control" placeholder="password" ng-model="password" />
          <button type="submit" class="btn btn-primary navbar-btn">Login</button>
        </form>
      </div>
    </div>

但是当我发出注销请求时,angular会添加一个额外的参数,请参阅rails server log:

Started DELETE "/sessions/destroy.json" for 127.0.0.1 at 2014-04-26 18:30:30 -0400
Processing by SessionsController#destroy as JSON
  Parameters: {"id"=>"destroy"}

为什么会这样?

1 个答案:

答案 0 :(得分:0)

试试这个:

angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
    return $resource('/sessions/:action',{}, {
      create: {method: 'POST', isArray: false},
      destroy: {method:'DELETE', params: { action: 'destroy.json' } }
    });
}])