使用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
依赖于在创建LoginController
时未加载的Google APIs Client Library for JavaScript
。所以我得到了gapi is not defined
,这完全有道理。
另一种解决方案是在gapi
加载后(在回调中)初始化$scope.userStatus
。但是,您如何告诉控制器更新$scope.userStatus
?
对于这类问题,有几种不同的方法。
在类似的情况下,我成功地使用$broadcast
注入了$rootScope
来发送依赖项中的事件,即gapiSetup
,然后可以根据需要在控制器、服务等中提取。
具体来说,使用$broadcast
可以解耦组件,还允许您在多个位置使用该事件,就像您需要更新除标头之外的其他位置一样。