【发布时间】:2016-05-18 03:13:18
【问题描述】:
我正在学习 Angular JS,但遇到了 cookie 问题。我有一个简单的登录工作正常,但是当我登录后刷新时,它会让我回到登录页面。我想设置cookie然后保持登录状态。
app.js
var myApp = angular.module('myApp', ['ngRoute', 'ngResource', 'ngCookies']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/', {
templateUrl: 'views/home.html',
controller: 'loginController'
}).
when('/admin', {
resolve: {
"check": function($location, $rootScope){
if(!$rootScope.loggedIn){
$location.path('/')
}
}
},
templateUrl: 'views/admin.html',
controller: 'loginController'
}).
otherwise({
redirectTo: '/'
});
}]);
loginController.js
myApp.controller('loginController', ['$scope', '$http', '$location', '$rootScope', 'userService', 'authService' '$cookies', function($scope, $http, $location, $rootScope, userService, authService, $cookies){
$scope.submitLogin = function(){
if($scope.username == 'admin' && $scope.password == 'admin'){
$rootScope.loggedIn = true;
//set date to 24 hours
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
//set cookie
$cookies.put('userName', $scope.username, {
'expires': expireDate
});
//get cookie
$rootScope.cookie = $cookies.get('userName');
$location.path('/admin');
} else {
alert("Wrong user name / password");
}
}
}]);
【问题讨论】: