2012-12-24 152 views
3

我有一個angularjs服務來獲取我的json數據。如何讓一個函數等待異步調用完成?

// Controller.js file 
$scope.data=Events.query(); 

$scope.getEventtypes = function(){ 
    angular.forEach($scope.data,function(value, key){ 
     var arr = []; 
     if(key==$scope.month+$scope.year) { 
      for(var i=0; i<key.length; i++) { 
       arr.push(value[i].type); 
       $scope.eventtypes=arr.unique(); 
      } 
     } 
    }); 
}; 

試圖訪問它拋出一個錯誤無法讀取的不確定財產typevalue[i].type。我知道這是因爲異步調用。

//i want to add success function like this 
$http.get('').success(function(data) { 
.... 
}); 

任何人都可以幫助我?如果你建議做一些比這更有效的事情會更好。謝謝

回答

2

雖然@Mahbub的建議是朝着正確的方向(承諾更容易協調異步功能),它不是唯一的技術。好的,舊的回調也會起作用。雖然承諾可以說是更加優雅的API,但它承諾API的苦澀事實並不支持作爲當前版本的AngularJS中$resource的一部分。

理論不談,在您的特定情況下,你可以簡單地使用一個回調,並用它做:

$scope.data=Events.query(function(data){ 

    angular.forEach(data,function(value, key){ 
     var arr = []; 
     if(key==$scope.month+$scope.year) { 
      for(var i=0; i<key.length; i++) { 
       arr.push(value[i].type); 
       $scope.eventtypes=arr.unique(); 
      } 
     } 
    }); 
}); 
+1

我知道回調但不推薦,因爲它可以成爲嵌套回調的噩夢,如你所知。我們已經在我們的開發項目中使用了pull請求的代碼,因爲它看起來很乾淨並標記爲「合併好」;) – Mahbub

1

爲了這個工作,$資源需要返回一個promise對象,像$ http一樣。但是,角度的最新版本還不支持。

Partap的pull被標記爲「很好合並」,它返回$資源的承諾。 https://github.com/angular/angular.js/pull/1547。你需要改變你的resource.js這個https://github.com/partap/angular.js/blob/005e865e5629a241d99c69a18f85fc2bb5abb1bc/src/ngResource/resource.js

文件,以便您可以使用和重新的因素你這樣的代碼

Events.query().$q.then(function(response){ 
$scope.data=response; 
.... 
.... 
}); 
5

我不得不使用asynchronuous $ HTTP服務(與JSONP)了類似的回答。

基本上你需要:

  • 使用回調或
  • 使用一個承諾對象

並承諾:

var promise = service.getHistoricalDataWithQ($scope.symbol, $scope.startDate, $scope.endDate); 

promise.then(function(data) { 
    $scope.items = data; 
});    

隨着回調:

service.getHistoricalDataWithCallback(function (data) { 
    $scope.items = data; 
}, $scope.symbol, $scope.startDate, $scope.endDate); 

查看答案Angular using $htp and YQL

查看我的jsFiddle