0

i'm setting up config params, but the console.log() returns me undefined and i can't understand why, i see the json returned from the http call in console!!!

app.run(function($rootScope, $location,$http){
        var update =  function (){
            $rootScope.config = {};
            $rootScope.config.app_name = "Appname";
            $rootScope.config.app_short_description = $rootScope.config.app_name+" helps you go out with your rabbit";
            $rootScope.config.app_motto = "hey ohhhhhhhhhh <i class='icon-check'></i>";
            $rootScope.config.app_url = $location.url();
            $rootScope.config.app_path = $location.path();
            $http.get('jsons/json.json').success(function(response) {
            $rootScope.config.app_genres =  response.data;

            });

            console.log($rootScope.config.app_genres);


        }  
        $rootScope.$on('$routeChangeStart', function(){ 
            update(); 
        });

    });
itsme
  • 48,972
  • 96
  • 224
  • 345

1 Answers1

4

Usually JavaScript is asynchronous, there are some exceptions; some old functions like alert are blocking. In AngularJS $http's methods are non-blocking.

So when you run;

$http.get('jsons/json.json').success(function(response) {
    $rootScope.config.app_genres = response;
});

console.log($rootScope.config.app_genres);

A request is sent out to jsons/json.json and the callback .success(function(response) { ... is not invoked until the request returns.

The code then continues directly to the console.log statement, where it logs undefined, as the callback has not yet been invoked.

What you should do to get the console.log to log the data, is put the log statement inside the callback like this:

$http.get('jsons/json.json').success(function(response) {
    $rootScope.config.app_genres = response;
    console.log($rootScope.config.app_genres);
});
Philipp Gayret
  • 4,870
  • 1
  • 28
  • 34
  • really clear now! but why it still returning undefined even with your example? :O – itsme Jan 22 '14 at 11:41
  • @RoyiNamir that depends on what sbaaaang is going to do with it, if it's some global shared config $rootScope could be Ok although AngularJS Services are probably better (?). – Philipp Gayret Jan 22 '14 at 11:42
  • yeah global configs but i can get http data to push inside :( – itsme Jan 22 '14 at 11:43
  • @sbaaaang if it _still_ is undefined you should check what `response.data` is, maybe it is just `reponse` you are looking for, try logging `response` completely. – Philipp Gayret Jan 22 '14 at 11:44