角度服务被调用两次

时间:2014-09-19 13:03:57

标签: angularjs authentication angular-services

我有以下角度服务:

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之后立即执行,以便页面导航回“/ login”。

为什么打印错误 - >真正?刷新后如何保持身份验证状态?

修改

感谢您的所有答案。关于身份验证的评论tutorial我跟随某人提到同样的问题。我最终明白他们的方法有点麻烦。 AuthenticationService除了检查$window.sessionStorage.token中是否存在令牌之外没什么作用,因此您可以使用某种存储方式。

我最后刚刚做了:

appServices.factory('AuthenticationService', function () {
    isLogged: function () {
        return $window.sessionStorage.token == true
    }    
})

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

    }
}

将.run(init)添加到应用底部的角度声明中:

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

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

答案 1 :(得分:1)

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

var auth = {
    isLogged: false
};

因此,在使用

登录后将其设置为true
AuthenticationService.isLogged = true;

那很好,直到你离开,你的javascript上下文丢失,一切都重新开始,此时它又一次是假的。

您已经在使用sessionStorage,因此您可能会坚持使用它,例如:

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

然后用

替换初始化程序
var auth = {
    isLogged: $window.sessionStorage.isLogged == "yeah" ? true : false
};

这是一个简单的例子,我可能会在你的服务上放置一个setLoggedIn或类似的东西,它会执行sessionStorage设置,所以你可以将它放在一个地方。