AngularJS全球HTTP轮询服务 [英] AngularJS global http polling service

查看:209
本文介绍了AngularJS全球HTTP轮询服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立使用AngularJS一个Web应用程序。该应用程序需要查询返回的JSON数据的URL,并做出数据提供给应用程序的任何部分。从我至今读,我最好的选择是建立一个处理轮询和保持JSON数据的自身的内部缓存中,然后注入服务为想要咨询该数据的应用程序的任何部分的服务。什么我失去的是如何真正去这样做。我发现最近的例子是<一个href=\"http://stackoverflow.com/questions/13937318/convert-angular-http-get-function-to-a-service\">this问题,但它似乎已创造了一个即是手动特定的控制器称为服务(这是自己绑在一个给定的路线),而我想要的东西,坚持在应用程序的后台运行,永远无论哪一部分的该应用是活动的。这是可行的,还是我走的是完全错误的做法?

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?

推荐答案

下面我的解决办法:

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)

<一个href=\"http://plnkr.co/edit/iMmhXTYweN4IrRrrpvMq?p=$p$pview\">http://plnkr.co/edit/iMmhXTYweN4IrRrrpvMq?p=$p$pview

编辑:由于乔希戴维·米勒在评论中建议,在此服务的依赖性应该app.run块被添加到确保轮询,从开始做的:

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

和也previous调用后下一次轮询调度移动完成。所以,就不会有调用的堆积的情况下,如果轮询挂起很长一段时间。

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.

更新plunker。

这篇关于AngularJS全球HTTP轮询服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆