angular.js - 如何用angular的run来将用户数据存储下来?

查看:71
本文介绍了angular.js - 如何用angular的run来将用户数据存储下来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想通过run来设置一个$rootScope.userinfo,然后不同页面里面也可以通过$rootScope.userinfo来获取当前用户的信息而不需要再去服务器抓取,但是现在遇到了挺多问题。
第一次我在run中直接$http然后设置$rootScope.userinfo=response,然后在各个controller当中通过$scope.userinfo=$rootScope.userinfo来将这个userinfo抓取到当前scope中使用,但是出现了undefined的问题;
第二次我在run中使用broadcast

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

然后再在controller里面使用$on

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

        });

但是出现了$on的function中的代码几乎从来不会运行的问题,似乎是因为run中的那个是异步的,controller的on在broadcast开始前就开始了?无论如何,反正也是错的多对的少。
所以不知道各位有什么好的方法可以给我借鉴一下?

解决方案

基本满足要求,可能有一丢丢副作用.

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

这篇关于angular.js - 如何用angular的run来将用户数据存储下来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆