2015-06-08 18 views
0

我喜歡這個創建服務:如何在服務數據準備好角度時做些什麼?

export class MDCurrencyService implements IMDCurrencyService { 

     httpService: ng.IHttpService; 
     handlerUrl: string; 

     constructor($http: ng.IHttpService) { 
      this.httpService = $http; 
      this.handlerUrl = '/Master/'; 
     } 


     get(): MDCurrency[]{ 
      var result: MDCurrency[] = []; 

      var resp: ng.IPromise<any> = this.httpService.get(this.handlerUrl +'GetAllCurrency') 
       .then((response: any): ng.IPromise<any> => this.handlerResponded(response, null)); 
      resp.then((data) => { 
       if (data.is_success) { 
        data.data.forEach(c => { 
         var converted: MDCurrency = <MDCurrency>c; 
         converted.selectedCountry = null; 
         converted.selectedStatus = null; 
         result.push(converted); 
        }); 
        return result; 
       } 
       else return null; 

      }); 
      return result; 
     } 

     handlerResponded(response: any, params: any): any { 
      response.data.requestParams = params; 
      return response.data; 
     } 




    } 

在我controller

$scope.currencies = this.currencies = mdCurrencyService.get(); 
      if ($scope.currencies.length > 0) { 
       console.log('entered'); //never executed 
       $scope.currencies.forEach(currency => { 
        for (var ii = 0; ii < this.statuses.length; ii++) 
         if ($scope.statuses[ii].Id == currency.Status) 
          currency.selectedStatus = this.statuses[ii]; 
       }); 
      } 

$scope.currencies後從forEach從未執行服務填補。 當$scope.currencies被服務中的數據填充時,如何執行該代碼?

+0

您是否已經在角度實現了'mdCurrencyService'?它是否會兌現承諾? – Magomogo

+0

是的,它返回,我想要處理該數據 – yozawiratama

回答

2

mdCurrencyService.get()應作爲返回承諾的異步服務來實現。它可以這樣使用:

mdCurrencyService.get().then(function (currencies) { 
    // process result here 
    $scope.currencies = currencies; 
}); 
+0

對不起,我的錯誤,mdCurrencyService.get()不返回承諾,我錯了嗎? – yozawiratama

+0

當然,mdCurrencyService應該是一個製作HTTP請求的服務。你可以在這裏查看文檔:https://docs.angularjs.org/api/ngResource/service/$resource – Magomogo

+0

好吧,所以它是我的錯誤,我想我可以返回以外的諾言,謝謝,你能完成你的答案嗎?我有錯誤的觀念?所以每個人都知道這是真的。再次感謝 – yozawiratama

相關問題