AngularJS global http polling service

前端 未结 3 1723
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 15:55

I\'m building a web app using AngularJS. The app needs to poll a URL that returns JSON data and make that data available to any part of the app. From what I\'ve read so far,

3条回答
  •  清歌不尽
    2020-12-12 16:31

    Here my solution:

    app.factory('Poller', function($http, $timeout) {
      var data = { response: {}, calls: 0 };
      var poller = function() {
        $http.get('data.json').then(function(r) {
          data.response = r.data;
          data.calls++;
          $timeout(poller, 1000);
        });      
      };
      poller();
    
      return {
        data: data
      };
    });
    

    (calls just to show that polling is been done)

    http://plnkr.co/edit/iMmhXTYweN4IrRrrpvMq?p=preview

    EDIT: As Josh David Miller suggested in comments, dependency on this service should be added in app.run block to ensure polling is done from start:

    app.run(function(Poller) {});
    

    And also moved scheduling of next poll after previous call finished. So there would not be "stacking" of calls in case if polling hangs for a long time.

    Updated plunker.

提交回复
热议问题