Dav*_*ave 85 javascript angularjs
我正在努力学习AngularJS.我第一次尝试每秒获取新数据:
'use strict';
function dataCtrl($scope, $http, $timeout) {
$scope.data = [];
(function tick() {
$http.get('api/changingData').success(function (data) {
$scope.data = data;
$timeout(tick, 1000);
});
})();
};
Run Code Online (Sandbox Code Playgroud)
当我通过将线程休眠5秒来模拟慢速服务器时,它会在更新UI并设置另一个超时之前等待响应.问题是当我重写上述内容以使用Angular模块和DI来创建模块时:
'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);
})();
};
Run Code Online (Sandbox Code Playgroud)
这仅在服务器响应很快时才有效.如果有任何延迟,它会在不等待响应的情况下每秒发送1个请求,并且似乎清除了UI.我想我需要使用回调函数.我试过了:
var x = Data.get({}, function () { });
Run Code Online (Sandbox Code Playgroud)
但得到一个错误:"错误:destination.push不是一个函数"这是基于$ resource的文档,但我真的不明白那里的例子.
如何使第二种方法起作用?
abh*_*aga 115
你应该tick在回调中调用函数query.
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query(function(){
$timeout(tick, 1000);
});
})();
};
Run Code Online (Sandbox Code Playgroud)
Bob*_*Bob 33
更新版本的angular引入了$ interval,它比$ timeout更好地用于服务器轮询.
var refreshData = function() {
// Assign to scope within callback to avoid data flickering on screen
Data.query({ someField: $scope.fieldValue }, function(dataElements){
$scope.data = dataElements;
});
};
var promise = $interval(refreshData, 1000);
// Cancel interval on page changes
$scope.$on('$destroy', function(){
if (angular.isDefined(promise)) {
$interval.cancel(promise);
promise = undefined;
}
});
Run Code Online (Sandbox Code Playgroud)
这是我使用递归轮询的版本。这意味着它将在启动下一次超时之前等待服务器响应。此外,当发生错误时,它将继续轮询,但会根据错误的持续时间以更轻松的方式进行。
var app = angular.module('plunker', ['ngAnimate']);
app.controller('MainCtrl', function($scope, $http, $timeout) {
var loadTime = 1000, //Load the data every second
errorCount = 0, //Counter for the server errors
loadPromise; //Pointer to the promise created by the Angular $timout service
var getData = function() {
$http.get('http://httpbin.org/delay/1?now=' + Date.now())
.then(function(res) {
$scope.data = res.data.args;
errorCount = 0;
nextLoad();
})
.catch(function(res) {
$scope.data = 'Server error';
nextLoad(++errorCount * 2 * loadTime);
});
};
var cancelNextLoad = function() {
$timeout.cancel(loadPromise);
};
var nextLoad = function(mill) {
mill = mill || loadTime;
//Always make sure the last timeout is cleared before starting a new one
cancelNextLoad();
$timeout(getData, mill);
};
//Start polling the data from the server
getData();
//Always clear the timeout when the view is destroyed, otherwise it will keep polling
$scope.$on('$destroy', function() {
cancelNextLoad();
});
$scope.data = 'Loading...';
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68110 次 |
| 最近记录: |