在 get 请求中使用 $interval
using $interval inside a get request
我在我的 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
}
我在我的 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
}