Angularjs路由侦听器不识别服务功能

时间:2014-05-20 13:21:24

标签: angularjs service routes

我已经为我的脚本实现了基于令牌的身份验证系统。我有一个简单的服务,检查用户是否登录。我使用此服务检查每次路由更改时的用户状态。奇怪的是;我可以登录很好,并注销没有问题。但如果我再次登录,我会收到此错误:

Error: AuthenticationService.isLogged is not a function

因此我的退出功能无效。如果我重新加载页面,错误消失,我可以退出就好了。

这是注销功能:

$scope.logout = function logout() {
            if (AuthenticationService.isLogged) {
                AuthenticationService.isLogged = false;
                localStorageService.remove('token');
                $location.path("/login");
            }
        }

这是路线监听器:

run(['AuthenticationService', '$rootScope', '$location', function(AuthenticationService, $rootScope, $location) {
    $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
        if (nextRoute.access.requiredLogin && !AuthenticationService.isLogged()) {
            $location.path("/login");
            $scope.apply();
        }
    });

服务;

module.factory('AuthenticationService', ['localStorageService', function(localStorageService) {
    var auth = {
        isLogged: function() {
            if (localStorageService.get('token')) {
                return true;
            } else {
                return false;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

工厂应该返回一个物体。

module.factory('AuthenticationService', ['localStorageService', function(localStorageService) {
        var auth = {
            isLogged: function() {
                if (localStorageService.get('token')) {
                    return true;
                } else {
                    return false;
                }
            }
        return auth;
        });

这应该有效,并且可以在http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/找到对工厂,服务和提供商的良好解读。

答案 1 :(得分:0)

Aboca在评论中提供了答案。我引用;

“AuthenticationService.isLogged = false< - 你正在杀掉这个函数,所以当你尝试AuthenticationService.isLogged()时,它说它不是一个函数,因为它是'false',只是去掉那个部分,它会运作良好“

非常感谢!

相关问题