gpt4 book ai didi

javascript - 如何每 10 秒调用一次 JS 函数,然后激活 Angular 中的函数

转载 作者:行者123 更新时间:2023-11-28 18:37:19 26 4
gpt4 key购买 nike

我正在尝试使用 highcharts 图表,并且想要“模拟”传入的实时数据,因此,当用户按下“开始实时流”按钮时,它会激活网页上的 JavaScript 功能,然后调用有大约 10 秒延迟的 Angular Controller 函数。

我可以从 Controller 查询 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
*/

});

最佳答案

您可以使用 Angular 的 $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();
}

关于javascript - 如何每 10 秒调用一次 JS 函数,然后激活 Angular 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com