I am developing a single page application with angularjs. I am cerating a simple login form to get user data and use it during session. But, if client refreshes the page, user info is removing and user routing to login page again.
I can not use cookie because user validate operation is done by a rest service.
How can I store user data on browser during session. user data should be delete on browser close.
<script>
var app = angular.module("MyApp", ["ui.router"]);
app.factory("AuthService", ["$rootScope",function($rootScope){
return {
setUserCredentials: function(user){
$rootScope.user = { isAuthenticated: true, username: user.username };
$rootScope.$emit('handleLogin', { user: user });
},
removeUserCreadentials: function(){
$rootScope.user = undefined;
},
isAuthenticated: function(){
return $rootScope.user != null;
},
getUser: function(){
return $rootScope.user;
}
}
}]);
app.run(function($rootScope, $state, AuthService){
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if(toState.authenticate && !AuthService.isAuthenticated()){
$state.transitionTo("login");
event.preventDefault();
}
});
$rootScope.$on("handleLogin",function(e, args){
console.log(e);
console.log(args);
$state.transitionTo("home");
});
$rootScope.$on("handleLogout",function(e, args){
console.log(e);
console.log(args);
});
});
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider.
state('home',{
url: '/home',
templateUrl: 'templates/home.html',
authenticate: true
}).
state('login',{
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController',
authenticate: false
});
$urlRouterProvider.otherwise("/login");
});
app.controller('LoginController', ["$scope", "AuthService", function($scope, AuthService){
$scope.login = function(){
if($scope.username == "myuser" && $scope.password == "123456"){
AuthService.setUserCredentials({ "username": "myuser" });
}
}
}]);
app.controller('HomeController', function($scope, $stateParams){
})
</script>
您可以使用html5中的sessionStorage新功能。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.