服务中的物业未更新

时间:2015-01-19 08:22:29

标签: javascript angularjs angular-ui-router

我的authentication服务有点麻烦。我的服务基本上都有这个:

angular.factory('authentication', [..., function() {
    var currentUser = {};

    return {
        login: function() {
            currentUser = { username: 'Foo' };
        },
        logout: function() {
            currentUser = {};
        }
        user: currentUser;
    }
})]

在我的AppCtrl中,我有这个:

 angular.module('App').controller('AppCtrl', [..., function() {
     $rootScope.$on('$stateChangeSuccess', function() {
         console.log(authentication.user);
     });
 }]);

在我的LogoutCtrl中,我有这个:

 angular.controller('LogoutCtrl', [..., function() {
     authentication.logout();
     $state.go('login');
 }]);

状态更改为login后,控制台仍会打印username: 'Foo'

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

angular.factory('authentication', [..., function() {
    var currentUser = {};

    return {
        login: function() {
            currentUser = { username: 'Foo' };
        },
        logout: function() {
            currentUser = {};
        }
        user: currentUser;
    }
})]

您的登录/注销方法会更改变量currentUser的值。这些更改不会传播到authentication.property

两种可能的修复方法:

1)使用this.user代替var currentUser

angular.factory('authentication', [..., function() {
    return {
        login: function() {
            this.user = { username: 'Foo' };
        },
        logout: function() {
            this.user = {};
        }
        user: {};
    }
})]

2)实施user作为基于getter的属性:

angular.factory('authentication', [..., function() {
    var currentUser = {};

    var auth = {
        login: function() {
            currentUser = { username: 'Foo' };
        },
        logout: function() {
            currentUser = {};
        }
    };

    Object.defineProperty(auth, 'user', {
        get: function() { return currentUser; }
    });

    return svc;
})]

答案 1 :(得分:1)

在对象中进行第一次分配时,您指的是用户的引用。然后在调用logout()时替换该引用,以便之前绑定的旧用户保持不变。将其更改为getter函数:

...
getUser: function() {
    return user; // always the correct reference
}

现在在console.log中调用它,它将起作用