簡體   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