0

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

    });
4

1 回答 1

4

通常 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来记录数据,将日志语句放在回调中,如下所示:

$http.get('jsons/json.json').success(function(response) {
    $rootScope.config.app_genres = response;
    console.log($rootScope.config.app_genres);
});
于 2014-01-22T11:39:46.010 回答