[英]How to watch for data change in json file
我想每次在json文件中有数据更改时更新我的视图,而无需手动刷新页面。 我使用以下方法进行一些数据轮询。 这是我获得$ http的服务文件
.service('employees', function ($http) {
this.getEmployees = function() {
return $http.get( './data/employee.json' );
};
这是我的控制器
.controller('The3Ctrl', function ($scope, employees, $interval) {
var _this = this;
$scope.getData = function() {
employees.getEmployees().then(function(response){
_this.items = response.data;
$scope.items = _this.items;
});
}
$scope.getData();
$interval(function(){
$scope.getData();
}, 10000);
这样,每10秒钟触发一次getData函数。 但是,我想要的是仅在数据(data.json)文件发生更改时才触发该函数。 如果没有数据更改,则触发该功能是没有用的。
您用“更改”指的是什么?问题是什么当视图不更新时,您可以使用$scope.$apply();
或者您可以通过以下方式检测到更改
$scope.$watch('element', function () {
console.error('element' + element + ' changes');
})
如果文件位于应用程序内部:
scope.$watch('Data', function(newValue, oldValue) {
if (newValue){
}
});
如果文件在服务器上:
您可以通过轮询来实现,轮询是通过旧的回调完成的,您可以重复调用它们而无需创建Promise的新实例。 它就像计时器一样工作,这是示例
var app = angular.module("myApp", []);
app.controller("The3Ctrl", ["$scope","$http","$timeout",
function($scope, $http,$timeout) {
var nextPolling;
var pollingInterval = 10000; // 10 seconds
var _polling = function ()
{
$http.get('./data/employee.json')
.success(function(data) {$scope.items = data;})
.error(function(data) {console.log('error');})
.finally(function(){ nextPolling = $timeout(_polling, pollingInterval); });
};
_polling();
$scope.$on('$destroy', function (){
if (nextPolling){
$timeout.cancel(nextPolling);
}
});
}]);
工作App
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.