Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - AngularJS global http polling service

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, my best bet is to create a service that handles the polling and keeps its own internal cache of the JSON data, and then inject the service into any part of the app that wants to consult that data. What I'm lost on is how to actually go about doing that. The closest example I've found is this question, but it appears to be creating a service that's manually called by a specific controller (which is itself tied to a given route), whereas I want something that persistently runs in the background of the app forever regardless of what part of the app is active. Is this doable, or am I taking the completely wrong approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...