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

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

问题描述

我正在使用 AngularJS 构建一个网络应用程序.应用程序需要轮询返回 JSON 数据的 URL,并使该数据可用于应用程序的任何部分.从我目前所读到的内容来看,我最好的办法是创建一个服务来处理轮询并保留自己的 JSON 数据内部缓存,然后将该服务注入到应用程序中想要查询该数据的任何部分.我迷失的是如何真正做到这一点.我发现的最接近的例子是这个问题,但是它似乎正在创建一个由特定控制器手动调用的服务(它本身与给定的路由相关联),而我想要一些永远在应用程序后台运行的东西,无论应用程序的哪个部分处于活动状态.这是可行的,还是我采取了完全错误的方法?

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)

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

正如 Josh David Miller 在评论中所建议的,应该在 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) {});

并且在上一次调用完成后移动了下一次轮询的调度.因此,如果轮询长时间挂起,则不会出现调用的堆叠".

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.

Updated plunker.

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

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