2017-09-22 47 views
0

我在頁面加載時觸發了2個異步API調用。我將他們每個人的價值彙總起來,然後計算他們的百分比變化。所以我需要確保每個API都已成功調用,並且在計算差異之前已經填充了包含總計的兩個變量。在執行操作之前等待2個異步API調用的結果

我現在所做的是用$watchGroup看兩個變量和調用函數時,這兩個變量不是null。這是我的控制器代碼:

module Controllers { 
    export class MyController { 
     static $inject = ["$scope",'$http']; 
     public TotalCurrent: any; 
     public TotalPrevious: any; 
     public diffPercent:any; 
     constructor(
      private $scope: ng.IScope, 
      private $http: ng.IHttpService, 
     ) { 
      this.$scope.$watchGroup(['myC.TotalCurrent', 'myC.TotalPrevious'], function (newVal, oldVal, scope) { 
       if (newVal[0] != oldVal[0] && newVal[1] != oldVal[1] && newVal[0] != null && newVal[1] != null) 
        scope.myC.diffPercent = scope.myC.GetDifferencePercent(newVal[0], newVal[1]); 
      }); 
       this.GetValuesFromAPI(); 
     } 


     public GetValuesFromAPI() { 
      this.TotalCurrent = null; 
      this.TotalPrevious= null; 


      this.$http.get("url1").then((result: any) => { 
       if (result.value.length > 0) { 
        var TempCurrentTotal = 0; 
        for (var i = 0; i < result.value.length; i++) { 
         TempCurrentTotal += result.value[i].Val; 
        } 
        this.TotalCurrent = TempCurrentTotal; 
       } 

      }); 

      this.$http.get("url2").then((result: any) => { 
        if (result.value.length > 0) { 
         var TempPreviousTotal = 0; 
         for (var i = 0; i < result.value.length; i++) { 
          TempPreviousTotal += result.value[i].Val; 
         } 
         this.TotalPrevious= TempPreviousTotal; 
        } 
       }) 
     } 

     public GetDifferencePercent(current:any, last:any){ 
      var percentage = ((Math.abs(current - last)/last) * 100).toFixed(2); 
      return percentage; 
     } 
    } 
} 

這現在工作得很好。但是,我想知道是否有什麼辦法可以實現這一點,而不必擔心與使用$watchGroup相關的性能問題,因爲將來API調用的數量可能會增加,並且我的頁面上還有其他幾個變量,如$watch。我認爲使用.then()鏈接API調用,但每個API都有相當大的響應時間,鏈接它們也會減慢頁面的速度。有什麼建議麼?

回答

2

你有沒有考慮過並行啓動它們?

您可以使用$q這樣的:

const promise1 = this.$http.get("url1"); 
const promise2 = this.$http.get("url2"); 

this.$q.all([promise1, promise2]).then(results => { 
    // results[0] is the result of the first promise, results[1] of the second. 
}); 

您可以在類的構造函數注入$ Q服務。

兩個承諾都完成時調用回調。你也可以檢查錯誤,如果你需要它,只需追加一個catch。

相關問題