如何从服务每秒发送$ http.get请求

时间:2016-02-09 11:48:41

标签: javascript jquery angularjs angular-services

我有一个有角度的应用程序,它有$ htto.get请求它工作正常,但我需要每隔一秒执行一次以带来新数据。

服务:

angular.module('adf.widget.liveCharts')
  .service('liveChartService', function($q, $http, $timeout){

    return {
      getJSON: function(path){
        var deferred = $q.defer();
        var url = 'http://orbit5.ds.cs.umu.se:8888/vrio/blk';
        $http.get(url)
          .success(function(data){
            if (data){
              deferred.resolve(data);
              } else {
                deferred.reject(data.data.message);
              }
            })
          .error(function(){
            deferred.reject();
          });
        return deferred.promise;
      }
  }
  });

在此处添加控制器以供参考

angular.module('adf.widget.liveCharts', ['adf.provider', 'highcharts-ng'])
  .config(function(dashboardProvider){
    // template object for github widgets
    var widget = {
      templateUrl: '{widgetsPath}/liveCharts/src/view.html',
      reload: true,
      resolve: {
        /* @ngInject */
        paths: function(liveChartService, config, $timeout){
          if (config.path){
            return liveChartService.getJSON(config.path);
          }

        }
      },
      edit: {
        templateUrl: '{widgetsPath}/liveCharts/src/edit.html'
      }
    };

2 个答案:

答案 0 :(得分:0)

在你的控制器中这样做。

$interval(function(){

    liveChartService.getJSON().then(function(data){

        //$scope.data = data;
    })
},1000);

答案 1 :(得分:0)

使用 $ interval 可以帮到你 - 它与vanilla js中的setInterval非常相似 - 基本上这就是结构

$ interval(fn,delay,[count],[invokeApply],[Pass]);

最后3个参数是可选的,但你需要以毫秒为单位传递函数+延迟时间,你可以使用任何函数,或者调用返回另一个函数的函数:

$interval(function(){
    liveChartService.getJSON().then(function(data){
        //some codes here
    })
},1000);

希望它对你有所帮助......