我正在使用 AngularJS 开发 SPA。登录后,将使用 token 创建一个 cookie,并将用户对象存储在 $rootScope.user
中,因为它们是动态加载的,因此可以方便地从各种 Controller 访问。
当我正常使用它并四处导航时,该应用程序工作正常。
当我使用 F5 刷新页面时,angular 被重新加载并且模块 run() 方法检查 cookie 是否存在并将用户从服务器重新加载到 $rootScope.user
。但是,在发生这种情况时,另一个 Controller 已经在期待 $rootScope.user
有一个用户。
如何在我的 $rootScope.user
准备好并加载之前阻止 Controller 初始化。如果可以,当然,如果有用户加载到 $rootScope
中,则检查 Controller 。但如果没有,$rootScope
如何调用 Controller 来执行一些初始化操作?
这是 app.run() 中的代码:
app.run(function ($rootScope, $location, $cookies, appServices) {
var token = $cookies.get('UserToken');
if (token) $rootScope.token = token;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
// Get user from server if token is there but no user
if ($rootScope.user == null) {
if ($rootScope.token) {
appServices.getUserByToken(token).then(function (d) {
if (d.Code == 1) {
$rootScope.user = d.ReturnObj;
if ($rootScope.user != null && next.templateUrl == "web/views/signin.html") $location.path("/dashboard");
} else $rootScope.goSignin(next.templateUrl);
});
}
else $rootScope.goSignin(next.templateUrl);
}
});
})
下面是动态加载的 Controller 中的示例代码:
app.registerCtrl('userdetailCtrl', function userdetailCtrl($scope, $http, $rootScope, $routeParams, appServices, $location, validationService) {
$scope.getOffices=function()
{
appServices.getOffices({ ID: $rootScope.user.OrgID, Token: $rootScope.token }).then(function (d){
if(d.Code==1){$scope.office = d.ReturnObj;}});
}
$scope.getOffices();
});
getOffices()
函数需要 $rootScope.user.OrgID
,因为尚未加载 $rootScope.user
而找不到.
有什么想法吗?
最佳答案
不确定这是否适用于您的情况,但是
$rootScope.$on('$includeContentLoaded', function () {
//fetch user here
}
解决了我遇到的类似问题
关于javascript - Angular : Reload $rootscope user before initializing controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739270/