I am learning Angular JS and am having issues with cookies. I have a simple login working fine, but when I refresh after logging in it takes me back to the login page. I want to set the cookie and then stay logged in.
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");
}
}
}]);
When you refresh the page $rootScope.loggedIn no longer exists. You need to check for the existence of the cookie rather than relying on a in memory variable.
I can't get the codepen working without all of the dependencies, but basically your resolve function should look something like this:
resolve: {
"check": function($location, $rootScope) {
var cookie = $cookies.get('userName');
console.log(cookie)
if (!cookie) {
$location.path('/')
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With