AngularJS身份验证服务+观察者

时间:2014-08-17 19:46:48

标签: angularjs

我正在为我的应用程序进行身份验证,而且我一直在努力让服务正常运行。我简化了代码。

服务:

App.factory('AuthenticationService', function() {
    var isLoggedIn = false;

    return {
        isLoggedIn : function() {
            return isLoggedIn;
        }
    }
});

MainController:

App.controller('MainController', [
    '$scope',
    'AuthenticationService',
    function( $scope, AuthenticationService ) {

        $scope.isLoggedIn = AuthenticationService.isLoggedIn();

        $scope.$watch('AuthenticationService.isLoggedIn()', function (newVal, oldVal) {
            console.log("Detected change in service.");
            if( newVal !== oldVal ) {
                $scope.isLoggedIn = newVal;
            }
        });
    }]);

的LoginController:

// Login HTTP request successful, returns a positive answer
// Now I want to change the variable in the service to True

AuthenticationService.isLoggedIn = true;

主要问题:现在从LoginController修改服务变量的方式 - 它没有反映在观察者中,我不确定它是否甚至更改了服务中的变量。有什么问题?

目标:成功登录后立即更改视图(ng-show)。

欢迎对代码提出任何其他建设性批评。

1 个答案:

答案 0 :(得分:1)

有几种方法。

1)使用广播事件
2)为您的服务创建一个范围:

App.factory('AuthenticationService', function($rootScope) {
    var isLoggedIn = false;
    var AuthenticationService = $rootScope.$new();
    return AuthenticationService;
});

3)你可以看一个房产:

App.factory('AuthenticationService', function() {
    return {
        isLoggedIn : false
    }
});

// In your controller:
 $scope.$watch('AuthenticationService.isLoggedIn', function(){...

4)你可以写一个自定义观察者:

App.factory('AuthenticationService', function() {
    var isLoggedIn = false;

    return {
        isLoggedIn : function() {
            return isLoggedIn;
        }
    }
});

// In your controller
$scope.$watch(function(){return AuthenticationService.isLoggedIn()}, function(){...