简体   繁体   English

Angular JS-无法将json放入$ rootScope

[英]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!!! 我正在设置配置参数,但console.log()返回的状态为undefined ,我不明白为什么,我看到控制台中http调用返回的json !!!

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; 通常JavaScript是异步的,有一些例外。 some old functions like alert are blocking. 一些旧功能(例如alert被阻止。 In AngularJS $http 's methods are non-blocking. 在AngularJS中, $http的方法是非阻塞的。

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. 将请求发送到jsons/json.json并且在请求返回之前不会调用回调.success(function(response) { ...

The code then continues directly to the console.log statement, where it logs undefined, as the callback has not yet been invoked. 然后,该代码直接直接继续到console.log语句,该语句记录未定义的位置,因为尚未调用该回调。

What you should do to get the console.log to log the data, is put the log statement inside the callback like this: console.log记录数据,您应该做的是将log语句放入回调中,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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