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都有相當大的響應時間,鏈接它們也會減慢頁面的速度。有什麼建議麼?