AngularJS启动会话

时间:2015-08-10 09:40:22

标签: javascript angularjs session cookies

我想在确认登录后开始新的会话。但是我得到了未定义的cookie而且无法完成。这是我的代码:

<script>
var app = angular.module('myApp', ['ngCookies'])
app.controller('loginController', function($scope, $http, $cookieStore) {   

    $scope.login = function() {

        $http.post("api/Login/" + $scope.email + "/"+ $scope.password).success(function(response) {          

            $scope.name = response;

            var userCookie = $cookies.get('newCookie');

            $cookies.put('newCookie', $scope.name);

        });

    };

});   
</script>

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:1)

Cookie尚未设置,因此您获得了未定义的Cookie。 你需要先设置cookie然后检索它。然后改变代码的顺序:

<script>
 angular.module('myApp', ['ngCookies'])
 .controller('loginController', loginController);

  function loginController($scope, $http, $cookies) {   
     $scope.login = function() {

        $http.post("api/Login/" + $scope.email + "/"+ $scope.password).success(function(response) {          

        $scope.name = response;

        $cookies.put('newCookie', $scope.name);
        var userCookie = $cookies.get('newCookie');
    });

   };

 }   
</script>