简体   繁体   English

Angular:在初始化控制器之前重新加载$ ​​rootscope用户

[英]Angular: Reload $rootscope user before initializing controller

I'm working on a SPA with AngularJS. 我正在使用AngularJS开发SPA。 After the sign in, a cookie is created with a token and a user object is stored in $rootScope.user which is conveniently accessible from various controllers as they are dynamically loaded. 登录后,使用令牌创建cookie,并将用户对象存储在$rootScope.user ,可以在动态加载时方便地从各种控制器访问。

The application works fine when I use it normally and navigate around. 当我正常使用并导航时,应用程序正常工作。

When I refresh a page with F5, angular is reloaded and the module run() method checks if the cookie exists and reloads the user from the server into $rootScope.user . 当我使用F5刷新页面时,会重新加载angular,模块run()方法会检查cookie是否存在,并将用户从服务器重新加载到$rootScope.user However, while this is happening, another controller is already expecting $rootScope.user to have a user. 然而,当发生这种情况时,另一个控制器已经期望$rootScope.user拥有一个用户。

How can I prevent controller initialization before my $rootScope.user is ready and loaded. 如何在$rootScope.user准备好并加载之前阻止控制器初始化。 If can, of course, check in the controller if there is a user loaded in $rootScope . 当然,如果可以检查控制器是否在$rootScope加载了用户。 But if there isn't, how can $rootScope invoke a controller to carry out some initialization? 但是如果没有, $rootScope如何调用控制器来执行一些初始化?

Here is code in app.run(): 这是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);
        }
    });
})

And here is sample code in a controller that is dynamically loaded: 以下是动态加载的控制器中的示例代码:

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();

});

The getOffices() function requires $rootScope.user.OrgID , which is not found as $rootScope.user is not yet loaded. getOffices()函数需要$rootScope.user.OrgID ,找不到$rootScope.user尚未加载。

Any ideas? 有任何想法吗?

Not sure if this will work in your situation, but 不确定这是否适用于您的情况,但是

$rootScope.$on('$includeContentLoaded', function () {
    //fetch user here
}

solved a similar issue that I had 解决了我遇到的类似问题

You can do several things, here's an example of two of these. 你可以做几件事,这里有两个例子。 Check the console in this fiddle 检查这个小提琴中的控制台

1. Watch the variable for changes: 1.观察变量的变量:

The first is watching $rootScope.user for changes in your controller: 第一个是在$rootScope.user中查看控制器中的更改:

App.run: App.run:

$timeout(function() {
    $rootScope.user = 'user';
}, 500)

in your controller: 在你的控制器中:

$rootScope.$watch('user', function(newVal, oldVal) {
   console.log(newVal, $rootScope.user); 
});

You can 'unwatch', too, if you don't want to keep executing code every time the user variable changes. 如果您不希望每次用户变量更改时都继续执行代码,也可以“取消监视”。

2. Emitting an event 2.发送活动

The second is emitting an event, and catching it where required, like this: 第二个是发出一个事件,并在需要的地方捕获它,如下所示:

App.run: App.run:

$timeout(function() {
    $rootScope.user = 'user';
    $rootScope.$broadcast('userEvent');
}, 500)

Your controller: 你的控制器:

$rootScope.$on('userEvent', function() {
    console.log($rootScope.user);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM