简体   繁体   中英

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. I using the following method to do some data polling. Here is my service file to get $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. However, What I want is for the function to only be triggered if there is a change in data (data.json) file. 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(); 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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