0

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.

3
  • 3
    Its async..... you are logging before setting.
    – Nix
    Apr 18, 2014 at 13:27
  • Your code snippet is missing brackets
    – Tim
    Apr 18, 2014 at 13:29
  • Yes, I was counting on to assume the syntax is correct.
    – pbd
    Apr 18, 2014 at 13:30

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.