0

I am initializing a function in my app run function with $rootScope like this -

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);
        });
    };
});

Now, when in a controller I am trying this -

angular.module('student').controller('ProfileController', function($scope,$http,$location,mvNotifier,$rootScope) {
    if(!$rootScope.user){
        $rootScope.getUser();
    }
    $scope.firstName = $rootScope.user.firstName;        
});

It works fine if the $rootScope.user is already set. but if it has to make a call to $rootScope.getUser() in that case it gives an error -

TypeError: Cannot read property 'firstName' of undefined

So, i am wondering may be its because getUser is an asynchronous call, if it is how do i fix this and if it isn't where am I going wrong, please suggest

2
  • 1
    all $http is asynchronous. My suggestion is to rewrite getUser to return the $http promise and use then in controller. You could cache the request so it doesn't have to hit server each time Commented Dec 20, 2014 at 5:34
  • thats what i thought, but how do i fix the error and apply the $scope.firstName after the call to $scope.getUser is completed Commented Dec 20, 2014 at 5:35

1 Answer 1

2

You could try something like this

$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')
    });
};

In controller:

$rootScope.getUser().then(function(user){
    $scope.firstName = user.firstName;    
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.