2014-09-19 57 views
0

我有以下的角服务:角服务被称为两次

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 
    }  
}) 
+1

你可能想看看ngStorage,或者某种存储机制.. – PSL 2014-09-19 13:16:18

+0

@PSL我不认为这是重点在这里。我想的更多的是等待第二个isLoggein = true或试图避免isLoggein = false。 – eskalera 2014-09-19 13:53:27

+0

对不起mybad。我正确阅读 – PSL 2014-09-19 14:06:04

回答

1

当页面加载时,您将它初始化为false at。

var auth = { 
    isLogged: false 
}; 

所以,当你用它设置为true登录后

AuthenticationService.isLogged = true; 

这很好,直到你naviage路程,你的JavaScript上下文丢失,一切又重新开始,此时它再一次假。

你已经在使用sessionStorage,所以你可以坚持这一点,即是这样的:

AuthenticationService.isLogged = true; 
$window.sessionStorage.isLogged = "yeah"; 

然后用

var auth = { 
    isLogged: $window.sessionStorage.isLogged == "yeah" ? true : false 
}; 

这是一个简单的例子取代你的初始化,我可能把setLoggedIn或类似的服务,它执行的sessionStorage设置,以便你的东西把它放在一个地方。

1

你可以试试这个:

function init($rootScope) { 
    $rootScope.$on('$routeChangeStart', function (event, next, current) { 

    } 
} 

而在您的应用程序的底部添加.RUN(INIT)到您的角度声明:

angular 
    .module('app', ['ngRoute']) 
    .config(config) 
    .run(init) 

它会在每次导航器刷新后调用。您可以将数据存储在$ window.sessionStorage中,并在每次刷新后对其进行测试。