我在angularjs中有以下代码.run()
所以当应用程序初始时,我在rootScope下设置了2个变量。 因为我决定在每个路线(页面)和控制器中使用这些变量。 异步如何在其他控制器中重新使用angularjs初始化变量
app.run(function($rootScope, $timeout, firebaseAuth) {
$rootScope.$on('firebaseLoggedIn', function(event, authUser) {
$timeout(function() {
$rootScope._isLoggedIn = true;
$rootScope._authUser = authUser;
},0);
});
但这里的问题,当我在控制器上运行它,它总是表现出不确定的。 除非我把它放在功能块。所以我的猜测是控制器在.run()
变量值之前运行 ;
app.controller('foo', function($scope){
console.log($scope._authUser); //Always undefined
//unless I do following
//$scope.clickme = function() {console.log($scope._authUser)};
});
任何建议我可以使用.run()中的变量(异步)?
如果我在每个控制器中调用下面的代码,似乎我不断重复自己。
$rootScope.$on('firebaseLoggedIn', function(event, authUser) {});
UPDATE 这是从哪儿firebaseLoggedIn事件。我想我不得不再提一提。回调是异步的。
app.service('firebaseAuth', ['$rootScope',
function($rootScope) {
//Define firebase DB url
this.firebaseRef = new Firebase("https://test.firebaseio.com");
this.onLoginStateChanges = new FirebaseAuthClient(this.firebaseRef, function(error, user) {
if (user) {
$rootScope.$emit("firebaseLoggedIn", user); //authenticated user
}
else if (error) {
$rootScope.$emit("firebaseLoginError", error); //authentication failed
}
else {
$rootScope.$emit("firebaseLogout"); //user not login
}
});
}]);
我试过但没有工作。在控制器中'FirebaseService.getIsLoggedIn()'返回false。我认为是因为它没有听取firebaseLoggedIn事件。请再次检查我的问题。我更新了它 – vzhen
尝试更改您的$ rootScope。$ emit到$ rootScope。$ broadcast。 $ emit是通过范围向上调度事件,$ broadcast是向下调度。 –
没有运气,也返回false – vzhen