客户端读取远程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;
});
});
目前用户通过重新加载网页来刷新状态。如何设置计时器(例如,每 2 秒一次)来轮询数据并自动刷新?
最佳答案
你可以使用 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);};
});
setInterval()
将在每个间隔延迟(2000 毫秒 === 2 秒)内持续执行您传递给它的函数,直到调用 clearInterval()
。在上面的示例中,我展示了如何清除 endLongPolling
中的间隔。
事实上, Angular 家伙已经为此提供了服务; $interval
.
$interval(fn, delay, [count], [invokeApply])
应用于您的场景将是:
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);};
});
关于javascript - 如何使用 AngularJS 定期轮询远程 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26051078/