Nithin P.H
Nithin P.H

Reputation: 732

using $interval inside a get request

I'm calling two API's in my init() but on the second get request i want it to keep calling it till a particular condition is satisfied( in my case 2 date ranges are passed ). The condition is that until the date difference is less than 15 days keep calling the API after that stop the API calls

My code goes like this

var startDate=moment(new Date()).format("YYYY-MM-DD");
var endDate;

$scope.init=function(){

 firstGetFunction().then(function(response1){
   let i=0;
   $interval(function() {
   endDate=moment(startDate).add(i++,'days').format("YYYY-MM-DD");
    if(new moment.duration(new Date(endDate)-new Date(startDate)).asDays()<=15){
      secondGetFunction(startDate,endDate).then(function(response2){
       $scope.obj1=response1;
       $scope.obj2=response2;
      });//2nd API call ends
     }//if diff is less than 15 days
     else{
       return;
     }
   },100);//$interval ends
 });//1st API call ends
}

The issue I'm facing is I'm not able to exit the $interval. Is there a better way to handle this Get request? Can the code be improved?

Upvotes: 0

Views: 38

Answers (1)

karaxuna
karaxuna

Reputation: 26940

Try this way:

var startDate=moment(new Date()).format("YYYY-MM-DD");
var endDate;

$scope.init=function(){

 firstGetFunction().then(function(response1){
   let i=0;
   let timer = $interval(function() {
   endDate=moment(startDate).add(i++,'days').format("YYYY-MM-DD");
    if(new moment.duration(new Date(endDate)-new Date(startDate)).asDays()<=15){
      secondGetFunction(startDate,endDate).then(function(response2){
       $scope.obj1=response1;
       $scope.obj2=response2;
      });//2nd API call ends
     }//if diff is less than 15 days
     else{
       $interval.cancel(timer);
     }
   },100);//$interval ends
 });//1st API call ends
}

Upvotes: 1

Related Questions