使用 AngularJS 进行服务器轮询 [英] Server polling with AngularJS
问题描述
我正在尝试学习 AngularJS.我第一次尝试每秒获取新数据成功了:
I'm trying to learn AngularJS. My first attempt to get new data every second worked:
'use strict';
function dataCtrl($scope, $http, $timeout) {
$scope.data = [];
(function tick() {
$http.get('api/changingData').success(function (data) {
$scope.data = data;
$timeout(tick, 1000);
});
})();
};
当我通过让线程休眠 5 秒来模拟慢速服务器时,它会在更新 UI 并设置另一个超时之前等待响应.问题是当我重写上述内容以使用 Angular 模块和 DI 进行模块创建时:
When I simulate a slow server by sleeping the thread for 5 seconds it waits for the response before updating the UI and setting another timeout. The problem is when I rewrote the above to use Angular modules and DI for module creation:
'use strict';
angular.module('datacat', ['dataServices']);
angular.module('dataServices', ['ngResource']).
factory('Data', function ($resource) {
return $resource('api/changingData', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
});
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query();
$timeout(tick, 1000);
})();
};
这仅在服务器响应快速时才有效.如果有任何延迟,它会在不等待响应的情况下每秒发送 1 个请求,并且似乎清除了 UI.我想我需要使用回调函数.我试过了:
This only works if the server response is fast. If there's any delay it spams out 1 request a second without waiting for a response and seems to clear the UI. I think I need to use a callback function. I tried:
var x = Data.get({}, function () { });
但出现错误:错误:destination.push 不是函数"这是基于 $resource 但我并没有真正理解那里的例子.
but got an error: "Error: destination.push is not a function" This was based on the docs for $resource but I didn't really understand the examples there.
如何使第二种方法奏效?
How do I make the second approach work?
推荐答案
您应该在 query
的回调中调用 tick
函数.
You should be calling the tick
function in the callback for query
.
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query(function(){
$timeout(tick, 1000);
});
})();
};
这篇关于使用 AngularJS 进行服务器轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!