【问题标题】:Running API call every 10 seconds每 10 秒运行一次 API 调用
【发布时间】:2017-11-06 19:09:03
【问题描述】:

我有以下方法返回一个 observable:

getWhatsUp() {
    return this.http.get('user/whatsUp?token=' + this.getToken())
                  .map((res:Response) => res.json())
                 .catch(
        err => {
            this.checkToken(err);
            return Observable.throw('Unverified token');
            }
      );
}

我在我的组件中使用它的方式如下:

ngOnInit() {
this.getWhatsUp();
}

getWhatsUp() {
    this.service.getWhatsUp()
                   .subscribe(
                     data => {
                        this.activities = data.activities;
                     },
                     error => { console.log("Error #333"); }
                     );
  }

如何每 10 秒运行一次以更新活动并确保 api 调用不会被堆叠和运行多次?

我知道interval 方法,但我不确定如何在我的设置中使用它

【问题讨论】:

    标签: angular


    【解决方案1】:

    为什么不只是:

    ngOnInit() {
        setInterval(() => this.getWhatsUp, 10000);
    }
    

    如果您需要有关语法的更多信息,请联系ES6 Arrow function again

    【讨论】:

      【解决方案2】:

      RxJS 方式

      ngOnInit(){
        let sec = 10;
        Observable.timer(0, sec * 1000).subscribe(this.getWhatsUp());
      }
      

      【讨论】:

        【解决方案3】:

        一种可能的解决方案是创建一个附加函数作为包含 setInterval 的处理程序。 setInterval(myTimer, 10000)

        ngOnInit() {
            this.getWhatsUpHandler();
        }
        
        getWhatsUpHandler(){
            setInterval(getWhatsUp, 10000);
        }
        
        getWhatsUp() {
            this.service.getWhatsUp()
                       .subscribe(
                         data => {
                            this.activities = data.activities;
                         },
                         error => { console.log("Error #333"); }
                         );
        }
        

        【讨论】:

          【解决方案4】:

          更好的解决方案是使用角度提供程序 $interval$destroy

          示例:由于此解决方案会破坏调用,如果当前状态/控制器发生更改

          var stop=$interval(function () {
                      function_call();
                  }, 12000)
          
                  $scope.stopInterval = function () {
                      if (angular.isDefined(stop)) {
                          $interval.cancel(stop);
                          stop = undefined;
                      }
                  };
          
                  $scope.$on('$destroy', function () {
                      // Make sure that the interval is destroyed too
                      $scope.stopInterval();
                  }); 
          

          【讨论】:

            猜你喜欢
            • 2022-01-11
            • 1970-01-01
            • 2011-08-06
            • 2012-12-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多