我正在学习 Angular JS,但在使用 cookie 时遇到了问题。我有一个简单的登录,工作正常,但是当我在登录后刷新时,它会带我回到登录页面。我想设置 cookie 然后保持登录状态。
应用程序.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: '/'
});
}]);
登录 Controller .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");
}
}
}]);
最佳答案
当您刷新页面时,$rootScope.loggedIn 不再存在。您需要检查 cookie 是否存在,而不是依赖内存中的变量。
如果没有所有依赖项,我无法让 codepen 工作,但基本上你的 resolve 函数应该看起来像这样:
resolve: {
"check": function($location, $rootScope) {
var cookie = $cookies.get('userName');
console.log(cookie)
if (!cookie) {
$location.path('/')
}
}
关于AngularJs Cookie 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281880/