我有以下的角服务:角服务被称为两次
appServices.factory('AuthenticationService', function() {
var auth = {
isLogged: false
}
return auth;
})
这TokenInterceptor
服务:
appServices.factory('TokenInterceptor', function ($q, $window, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
console.log(AuthenticationService.isLogged)
return response || $q.when(response);
}
};
});
我推入$httpProvider
$httpProvider.interceptors.push('TokenInterceptor');
而且
$routeProvider.
when('/', {
templateUrl: 'partials/index',
controller: IndexCtrl,
access: { requiredLogin: true }
})
在AuthenticationService.isLogged = true
登录后,如果我浏览到路径“/”通过agular按钮,一切正常,但是当页面被刷新的AuthenticationService再次实例化,我可以看到console.log(AuthenticationService.isLogged)
打印false
并打印true
后inmediately所以页面导航回“/登录”。
为什么它打印false - > true?刷新后我能做些什么来保持身份验证状态?
编辑:
感谢您的答案。关于认证tutorial的评论,我在跟随某人提到相同的问题。我最终了解到他们的方法有点麻烦。 AuthenticationService
不仅仅是检查$window.sessionStorage.token
中令牌的存在,因此您对于使用某种存储来说是完全正确的。
最后我只是在做:
appServices.factory('AuthenticationService', function() {
isLogged: function() {
return $window.sessionStorage.token == true
}
})
你可能想看看ngStorage,或者某种存储机制.. – PSL 2014-09-19 13:16:18
@PSL我不认为这是重点在这里。我想的更多的是等待第二个isLoggein = true或试图避免isLoggein = false。 – eskalera 2014-09-19 13:53:27
对不起mybad。我正确阅读 – PSL 2014-09-19 14:06:04