Search code examples
angularjsrootscope

$rootscope not holding value


I am using the following code to store username ('pqr') value in rootscope but it is scoped by $http.get mehtod

angular.module('myApp').run(function ($rootScope,$http) {
    $rootScope.username = 'abc';
    $http.get('/api/getuser')
        .success(function(data) {
            console.log("logged in user is: "+data);
            $rootScope.username = data;
        });
    $rootScope.$on('$routeChangeStart', function (event, next) {
    });
    console.log("logged in user after setting: " + $rootScope.username);
});

The console log outputs are:

logged in user is: pqr
logged in user after setting: abc

How can I set the $rootScope.username to pqr out of scope of $http.get method

EDIT: Added closing brackets.


Solution

  • This should be closed, because its an async issue... run this code and you will see.

    angular.module('myApp').run(function ($rootScope,$http) {
     $rootScope.username = 'abc';
     var $promise = $http.get('/api/getuser')
        .success(function(data) {
          console.log("logged in user is: "+data);
          $rootScope.username = data;
        });
     $rootScope.$on('$routeChangeStart', function (event, next) {
    
     });
     $promise.then(function(){
         console.log("logged in user after setting: "+$rootScope.username);
     });