watching angularjs $rootScope variables

475 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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