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

    });

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

really clear now! but why it still returning undefined even with your example? :O
@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 (?).
yeah global configs but i can get http data to push inside :(
@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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.