如何使用AngularJS定期轮询远程json?

ohh*_*hho 1 javascript angularjs

客户端读取远程json:

app.controller("StatusController", function($scope, $http) {

  $http.defaults.headers.common["X-Custom-Header"] = "Angular.js";
  $http.get('https://example.com/status.json').
    success(function(data, status, headers, config) {
      $scope.status = data;
    });

});
Run Code Online (Sandbox Code Playgroud)

目前,用户通过重新加载网页来刷新状态.如何设置计时器(例如,每2秒)轮询数据并自动刷新?

agc*_*nti 7

你可以使用setInterval():

app.controller("StatusController", function($scope, $http) {

  $http.defaults.headers.common["X-Custom-Header"] = "Angular.js";

  this.interval = setInterval(function(){$http.get('https://example.com/status.json').
    success(function(data, status, headers, config) {
      $scope.status = data;
    });}, 2000);

  this.endLongPolling = function(){ clearInterval(this.interval);};

});
Run Code Online (Sandbox Code Playgroud)

setInterval()将继续执行您在每个间隔延迟时传递给它的函数(2000毫秒=== 2秒),直到clearInterval()被调用.在上面的例子中,我展示了如何清除间隔endLongPolling.

事实上,有角度的家伙已​​经为此服务了; $interval.

$interval(fn, delay, [count], [invokeApply])
Run Code Online (Sandbox Code Playgroud)

适用于您的方案,它将是:

app.controller("StatusController", function($scope, $http, $interval) {

  $http.defaults.headers.common["X-Custom-Header"] = "Angular.js";

  this.interval = $interval(function(){
    $http.get('https://example.com/status.json').
      success(function(data, status, headers, config) {
        $scope.status = data;
  });}, 2000);

  this.endLongPolling = function(){ $interval.cancel(this.interval);};

});
Run Code Online (Sandbox Code Playgroud)