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都有相当大的响应时间,链接它们也会减慢页面的速度。有什么建议么?