如何每10秒调用一次JS函数,然后激活角度函数

时间:2016-04-26 06:50:11

标签: javascript angularjs highcharts

我正在尝试使用highcharts图表,我想“模拟”进入的实时数据,因此,当用户按下“开始实时流”按钮时,它会激活一个函数,我想在网页上使用JavaScript,然后调用具有大约10秒延迟的角度控制器功能。

我可以从控制器查询json数据的方式来自http请求,我使用了几周后我想查询数据的时间(我早在100周之后)。所以我想在网页上有一个函数,从99和100开始,并将变量传递给angular函数,以便在100-99周前查询并将数据添加到图表中。等待10秒,然后立即查询99-98直到它变为零。

我对JS很新,所以我不太清楚如何开始,但我已经阅读了有关setTimeout函数的内容。任何建议或更好的方式去做这件事将非常感激。

我当前的http请求看起来像这样并且是静态的:

$http({
           url: '/api/v1/datapoints',
           method: 'POST',    
           data: '{"start":"99w-ago","end":"98w-ago","tags":[{"name":"SolarData"}]}'
         }).then(function(predixTimeSeriesData){
                 $scope.solarData = predixTimeSeriesData.data.tags[0].results[0].values.map(
             function(curVal, index, arr) {
                return [curVal[0], curVal[1]];
                }
                );
        console.log($scope.solarData);
        /*
          I use $scope.solatData in my chart on the html page like
          <line-series-chart data={{solarData}}></line-series-chart>
          so this is why I am thinking I need to have the time interval on the view page 
          instead of the controller because i cannot control my chart from there
        */

        });

1 个答案:

答案 0 :(得分:3)

您可以使用角度的$interval服务,如下所示:

function myController($scope, $http, $interval) {

    var currentWeek = 99;
    var fetchInterval;

    $scope.solatData = [];

    $scope.fetch = function() {
        $http.get("someUrl", {
            params: {
                week: currentWeek
            }
        }).then(function(data){
            // This will also update your graph, assuming it is implemented
            // to watch changes on the data
            $scope.solatData = $scope.solatData.concat(data);
            currentWeek++;
        });
    }

    $scope.start = function() {
        fetchInterval = $interval($scope.fetch, 10000);
    }

    // Clear the interval when the scope/controller is 'destroyed'
    $scope.$on('$destroy', function() {
        $interval.cancel(fetchInterval);
    });

    // kick off initial start
    $scope.start();
}