繁体   English   中英

Angular JS-无法将json放入$ rootScope

[英]Angular js - can't get json into $rootScope

我正在设置配置参数,但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(); 
        });

    });

通常JavaScript是异步的,有一些例外。 一些旧功能(例如alert被阻止。 在AngularJS中, $http的方法是非阻塞的。

所以当你跑步时

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

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

将请求发送到jsons/json.json并且在请求返回之前不会调用回调.success(function(response) { ...

然后,该代码直接直接继续到console.log语句,该语句记录未定义的位置,因为尚未调用该回调。

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