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