Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 监视angularjs$rootScope变量_Javascript_Angularjs_Rootscope - Fatal编程技术网

Javascript 监视angularjs$rootScope变量

Javascript 监视angularjs$rootScope变量,javascript,angularjs,rootscope,Javascript,Angularjs,Rootscope,我正在使用$rootScope在我的应用程序运行函数中初始化一个函数,如下所示- angular.module('student').run(function($sce,$rootScope, $location,mvNotifier,$http) { $rootScope.getUser = function(){ var url = '/getUser'; $http({method:'POST',url:url}).success(function(

我正在使用$rootScope在我的应用程序运行函数中初始化一个函数,如下所示-

angular.module('student').run(function($sce,$rootScope, $location,mvNotifier,$http) {
    $rootScope.getUser = function(){
        var url = '/getUser';
        $http({method:'POST',url:url}).success(function(data,status,headers,config){
            if(status==200){
                $rootScope.user = data;
                var date = new Date(data.date);
                $rootScope.user.joinMonth=date.toUTCString().split(' ')[2];
                $rootScope.user.joinYear=date.getYear();     
            }
            else
                mvNotifier.error(data.reason);
        });
    };
});
现在,当我在控制器中尝试时-

angular.module('student').controller('ProfileController', function($scope,$http,$location,mvNotifier,$rootScope) {
    if(!$rootScope.user){
        $rootScope.getUser();
    }
    $scope.firstName = $rootScope.user.firstName;        
});
如果已设置$rootScope.user,则可以正常工作。但是如果在这种情况下它必须调用$rootScope.getUser(),它会给出一个错误-

TypeError: Cannot read property 'firstName' of undefined

所以,我想知道这可能是因为getUser是一个异步调用,如果它是我如何解决这个问题,如果它不是我出了什么问题,请建议您可以尝试类似的方法

$rootScope.getUser = function () {
    var url = '/getUser';
    return $http({
        method: 'POST',
        url: url,
        cache: true /* cache true so we don't have to get from server each time*/
    }).then(function (resp) {
        var data = resp.data;
        $rootScope.user = data;
        var date = new Date(data.date);
        $rootScope.user.joinMonth = date.toUTCString().split(' ')[2];
        $rootScope.user.joinYear = date.getYear();
        return $rootScope.user;
    }, function(err){
       alert('OOps server errror')
    });
};
在控制器中:

$rootScope.getUser().then(function(user){
    $scope.firstName = user.firstName;    
});

所有
$http
都是异步的。我的建议是重写
getUser
以返回
$http
承诺并在控制器中使用
then
。您可以缓存请求,这样它就不必每次都命中服务器。这正是我的想法,但是在对$scope.getUser的调用完成后,如何修复错误并应用$scope.firstName呢