Question

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

    });
Était-ce utile?

La solution

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);
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top