[英]Single page application store store user data
我正在使用angularjs開發一個單頁應用程序。 我正在確定一個簡單的登錄表單,以獲取用戶數據並在會話期間使用它。 但是,如果客戶端刷新頁面,則將刪除用戶信息,並且用戶將再次路由到登錄頁面。
我不能使用cookie,因為用戶驗證操作是由rest服務完成的。
會話期間如何在瀏覽器中存儲用戶數據。 用戶數據應在瀏覽器關閉時刪除。
<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新功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.