简体   繁体   中英

Angular js - can't get json into $rootScope

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

    });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM