angular.js - How to use angular's run to store user data?
怪我咯
怪我咯 2017-05-15 17:07:45
0
1
814

I want to set a $rootScope.userinfo through run, and then in different pages, I can also use $rootScope.userinfo to obtain the current user's information without going to the server to crawl it, but now I have encountered a lot of problems.
For the first time, I directly $http in run and then set $rootScope.userinfo=response, and then used $scope.userinfo=$rootScope.userinfo in each controller to capture this userinfo into the current scope for use, but An undefined problem occurred;
The second time I used broadcast in run

        $rootScope.$broadcast("thisintheuserinfo", response);

Then use $on

in the controller
$scope.$on("thisintheuserinfo",
        function (event, msg) {
            if(msg){
                //$scope.usernamea = msg.user;
                console.log('123')
                console.log(msg)
            }
            else{
                alert(msg)
            }

        });

But there is a problem that the code in the $on function almost never runs. It seems that because the one in run is asynchronous, the controller's on starts before the broadcast starts? No matter what, there are more wrong and less right.
So I don’t know if you have any good methods that I can learn from?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
刘奇

Basically meets the requirements, there may be a few side effects.

var app = angular.module('myApp', []);

app.factory('User', function($q, $timeout){
    var userInfo, 
        loading, 
        deferred = $q.defer(),
        promise  = deferred.promise;

    return {
        getUserInfo: function(){

            if(!loading){
                loading = true;
                // 模拟http请求
                console.log('发起请求...')
                $timeout(function(){
                    userInfo = {
                        name: 'Angularjs',
                        version: '1.x'
                    };
                    deferred.resolve(userInfo);

                }, 100);

                return promise;

            }else if( userInfo ){
                console.log('这是缓存的信息');
                return $q.resolve(userInfo);
            }else{
                console.log('正在等待请求的结果...');
                return promise;
            }
        }
    }
});

app.controller('MyCtrl',function($scope, User, $timeout){
    User.getUserInfo().then(function(userInfo){
        console.log('run:',userInfo);
        $scope.name = userInfo.name;
    });
});

app.run(function(User){
    User.getUserInfo().then(function(userInfo){
        console.log('controller:',userInfo);
    });
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template