2013-07-19 61 views
2

我想從json讀取數據,並等待數據將被提取到$ scope.urls.content。所以我寫代碼:

$scope.urls = { content:null}; 
$http.get('mock/plane_urls.json').success(function(thisData) { 
    $scope.urls.content = thisData;  
}); 

而現在我正在嘗試寫一些類似回調但不起作用。我怎樣才能做到這一點?還是有這個功能嗎?我正在用盡想法;/

+1

你寫的東西已經包含回調。請解釋你想要達到的目標。 – finishingmove

+1

你在開發工具的網絡選項卡中看到什麼,你有沒有從服務器響應?它的代碼是20x嗎?你只是定義成功回調,這意味着它不會在失敗的情況下被解僱。 – vittore

+0

我想使用數據是什麼被提取到$ scope.urls.content但每次當我嘗試使用它立即他們有空。 – Mariola

回答

2

你的意思是?

$http.get('mock/plane_urls.json').success(function(thisData) { 
    $scope.urls.content = thisData; 
    $scope.yourCallback(); 
}); 
$scope.yourCallback = function() { 
    // your code 
}; 
+0

我確定'yourCallBack'會帶上返回數據的參數:)。 – tymeJV

+1

我相信應該使用promise API而不是直接調用回調。它是專爲這些需要.. –

1

你想promises$resource工作。

由於$http本身返回一個承諾,你所要做的就是鏈接到它的返回。就這麼簡單:

var promise = $http.get('mock/plane_urls.json').then(function(thisData) { 
    $scope.urls.content = thisData; 
    return 'something'; 
}); 

// somewhere else in the code 
promise.then(function(data) { 
    // receives the data returned from the http handler 
    console.log(data === "something"); 
}); 

我做了一個非常簡單的小提琴here

但是,如果您需要不斷調用此信息,則應該通過服務將其公開,以便任何人都可以獲取其結果並對其進行處理。即:

service('dataService', function($http) { 
    var requestPromise = $http.get('mock/plane_urls.json').then(function(d) { 
    return d.data; 
    }); 

    this.getPlanesURL = function() { 
    return requestPromise; 
    }; 
}); 

// and anywhere in code where you need this info 
dataService.getPlanesURL().then(function(planes) { 
    // do somehting with planes URL 
    $scope.urls.content = planes; 
}); 

只是一個重要的說明。我嘲笑的這項服務將緩存並始終返回相同的數據。如果您需要多次調用此JSON,那麼您應該使用$resource