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 に答える