0

我正在使用 $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 是一个异步调用,如果它是我如何解决这个问题,如果它不是我哪里出错了,请建议

4

1 回答 1

2

你可以试试这样的

$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;    
});
于 2014-12-20T05:52:47.957 回答