例如:我的数组中有两个值。 ar = [1,2]
我希望 api 调用的方式如下:在时间 T 时,我使用参数 1 调用函数,在 T + 20 时,使用参数 2 调用函数,20 秒后再次使用参数 1 调用函数,依此类推。
我的解决方案
export default class MyComponent {
arr = [1, 2];
paramIndex = 0;
T = 1000;
ngOnInit() {
setTimeout(() => {
this.toggleParam();
}, T);
/// notice that T is integer you should assign at first as example i will set it equal 1 second
}
toggleParam() {
if(paramIndex == 0)
paramIndex = 1;
else
paramIndex = 0;
this.apiCall(arr[paramIndex]);
setTimeout(()=> {
this.toggleParam();
}, 20)
}
apiCall(myParam) {
}
}
谢谢你们的帮助,我找到了一种使用计数器来解决上述场景的方法,如下所示:
arr=[1,2]
counter = 0
apiCall(){
this.timerSub = Observable.interval(20000).subscribe(() => {
const displayCond = counter % 2;
if (displayCond === 0) {
// call API using 1st item in array
}
else{
// call API using 2nd item in array
}
}