简体   繁体   English

如何在json文件中监视数据更改

[英]How to watch for data change in json file

I want to update my view each time there is data change in json file without manually refreshing page. 我想每次在json文件中有数据更改时更新我的​​视图,而无需手动刷新页面。 I using the following method to do some data polling. 我使用以下方法进行一些数据轮询。 Here is my service file to get $http 这是我获得$ http的服务文件

.service('employees', function ($http) {
    this.getEmployees = function() {
      return $http.get( './data/employee.json' );
    };

This is my controller 这是我的控制器

.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);

With this the getData function is triggered every 10 seconds. 这样,每10秒钟触发一次getData函数。 However, What I want is for the function to only be triggered if there is a change in data (data.json) file. 但是,我想要的是仅在数据(data.json)文件发生更改时才触发该函数。 If there is no data change, it's useless for the function to be triggered. 如果没有数据更改,则触发该功能是没有用的。

What do you refer with "change" or what is the problem When the view doesnt update you can use $scope.$apply(); 您用“更改”指的是什么?问题是什么当视图不更新时,您可以使用$scope.$apply(); or you can detect a change with 或者您可以通过以下方式检测到更改

$scope.$watch('element', function () {
    console.error('element' + element + ' changes');
})

If the file is inside the App: 如果文件位于应用程序内部:

 scope.$watch('Data', function(newValue, oldValue) {
 if (newValue){

   }
  });

If the file is on Server: 如果文件在服务器上:

You can achieve this through polling, Polling is done with old callbacks, you can call them repeatedly without need to create new instance of the promise. 您可以通过轮询来实现,轮询是通过旧的回调完成的,您可以重复调用它们而无需创建Promise的新实例。 It works like timer, here is the sample 它就像计时器一样工作,这是示例

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);
            }
        });


    }]);

Working App 工作App

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM