このように $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 は非同期呼び出しであるため、これをどのように修正すればよいのか、どこが間違っているのか、提案してください。