【问题标题】:How to toggle parameters in API call on a fixed INterval in Angular 4?如何在 Angular 4 中的固定间隔上切换 API 调用中的参数?
【发布时间】:2018-02-25 05:47:23
【问题描述】:

例如:我在一个数组中有两个值。 arr = [1,2]

我希望以这样的方式调用 api,在时间 T,我用参数 1 调用一个函数,在 T + 20,用参数 2,然后在 20 秒后,用参数 1 再次调用,依此类推。

【问题讨论】:

    标签: javascript angular typescript observable


    【解决方案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) {
    
        }
    }
    

    【讨论】:

    • 好吧...酷!我通过使用计数器并检查偶数条件找到了一条出路,如下所示:
    • this.timerSub = Observable.interval(20000).subscribe(() => { const displayCondition = counter % 2; if (displayCondition === 0) { ..Do Your Code } else{ ..做你的代码...}
    【解决方案2】:

    谢谢大家的帮助,我在上面的场景中找到了使用计数器的方法,如下:

    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
              }
    }

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2021-09-02
      • 2022-06-10
      • 2011-06-04
      相关资源
      最近更新 更多