0

我创建了ui-router一个状态,它有一个显示当前用户状态的视图。以下代码获取当前用户状态:

var sydney = sydney || {};
sydney.checkAuth = function() {
    gapi.auth.authorize({
        client_id : sydney.CLIENT_ID,
        scope : sydney.SCOPES,
        immediate : true
    }, sydney.handleAuthResult);
}

sydney.handleAuthResult = function(authResult) {
    if (authResult) {
        // The user has authorized access
        console.log("User is signed in");
    } else {
        // User has not Authenticated and Authorized
        console.log("User is not signed in");
    }
}

state定义为:

$stateProvider
.state('route1', {
    url: "/route1",
    views : {
        "headerView" : {
            templateUrl : 'partials/header.html',
            controller: 'LoginController'
        },
        "navigationView" : {
            templateUrl : 'partials/navigation.html',
            controller: 'NavigationController'
        },
        "contentView": {
            templateUrl : 'partials/content1.html'
        }
    }
})  

LoginController: _

function LoginController($scope, $state) {
    $scope.checkUserStatus = function() {
        sydney.checkAuth();
    }
}

我需要粘合所有这些部分,所以当headerView显示 时,我可以显示用户状态(登录或未登录)。

我做的第一件事是在 中创建一个变量LoginController来保存状态

$scope.userStatus = sydney.checkAuth();

问题是它sydney.checkAuth依赖于在创建Google APIs Client Library for JavaScript时未加载的LoginController。所以我明白gapi is not defined这完全有道理。

另一种解决方案是在加载$scope.userStatus后初始化gapi(在回调中)。但是你如何告诉控制器更新$scope.userStatus呢?

4

1 回答 1

0

对于这类问题,几乎没有不同的方法。

在类似的情况下,我已经成功注入$rootScope使用$broadcast从依赖项发送事件,即gapiSetup- 然后可以根据需要在您的控制器、服务等中获取它。

具体来说,使用$broadcast解耦组件,还允许您在多个地方使用该事件 - 就像您需要更新其他地方而不仅仅是您的标题一样。

于 2013-07-02T22:26:44.520 回答