Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在get请求中使用$interval_Javascript_Angularjs_Promise_Momentjs_Intervals - Fatal编程技术网

Javascript 在get请求中使用$interval

Javascript 在get请求中使用$interval,javascript,angularjs,promise,momentjs,intervals,Javascript,Angularjs,Promise,Momentjs,Intervals,我在init中调用了两个API,但是在第二个get请求中,我希望它继续调用它,直到满足我的案例中的一个特定条件,并且传递了2个日期范围。条件是,在日期差小于15天之前,继续调用API,然后停止API调用 我的代码是这样的 var startDate=moment(new Date()).format("YYYY-MM-DD"); var endDate; $scope.init=function(){ firstGetFunction().then(function(response1){

我在init中调用了两个API,但是在第二个get请求中,我希望它继续调用它,直到满足我的案例中的一个特定条件,并且传递了2个日期范围。条件是,在日期差小于15天之前,继续调用API,然后停止API调用

我的代码是这样的

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
}
我面临的问题是我无法退出$interval。 是否有更好的方法来处理此Get请求? 代码可以改进吗?

尝试以下方法:

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
}