简体   繁体   English

经常使用 angularjs 中的 http 调用从 REST API 请求数据

[英]frequently requesting data from REST API using http call in angularjs

I am new to angularjs and D3.我是 angularjs 和 D3 的新手。 Here I am going to to implement real time line chart using D3.这里我将使用 D3 实现实时折线图。 I am retrieving data from external REST API, by using angulrjs http call.我正在通过使用 angulrjs http 调用从外部 REST API 检索数据。 But the problem is, I don't know how to request data frequently from the REST API using http call.但问题是,我不知道如何使用 http 调用频繁地从 REST API 请求数据。

If you absolutely can't use web sockets then checkout $interval.如果您绝对不能使用网络套接字,请查看 $interval。 https://docs.angularjs.org/api/ng/service/$interval https://docs.angularjs.org/api/ng/service/$interval

Basically this allows you to execute a function over and over again with a specified delay.基本上,这允许您以指定的延迟一遍又一遍地执行函数。

For example:例如:

(function () {
'use strict';
angular
    .module('app')
    .controller('TestController', TestController);

TestController.$inject = ['$interval'];

function TestController($interval) {
    var vm = this;

    //Perform doSomething every 10000 ms
    $interval(doSomething, 10000);

    function doSomething() {
         //some logic here
    }       
}

})();

In the above code the function doSomething will be called every 10000ms.在上面的代码中,函数 doSomething 将每 10000 毫秒调用一次。

So you in your case you can place your request inside doSomething and update your scope with the response from your rest api.因此,在您的情况下,您可以将请求放在 doSomething 中,并使用来自您的 rest api 的响应更新您的范围。

NB: This works but is not necessarily the best solution.注意:这有效,但不一定是最佳解决方案。 Something like Signal R with websockets would be a better solution.像带有 websockets 的 Signal R 这样的东西将是更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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