Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using a $watchGroup to monitor their changes. Here is my controller code:
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;
}
}
}
While the current method works well, I am concerned about potential performance issues with increasing API calls in the future. Is there an alternative approach to achieve this without relying on $watchGroup considering the response times of each API call and the impact on page speed when chaining them? Any suggestions would be appreciated.