我想从这个页面http://orbit5.ds.cs.umu.se:8888/vrio/debug/blk获取一些数据。每次刷新页面时,此页面上的数据都会更新。所以我想要这些更新的值。为了更新这些值,我可以使用 $timeout 但随后我需要以某种方式在 getdata 之外获取这些值,因为我想将这些值插入到另一个函数中以制作图表,否则整个图表将在每次该函数时继续呈现更新。我无法获取函数之外的值,我在 stackoverflow 上找到了这个答案但据我所知,大多数答案都使用函数内部的数据。
如何在 JavaScript 函数之外获取更新后的值并将其插入另一个函数?或者也许有另一种更好的方法来解决这个问题?
我的代码:
function getData(){
var data;
$http.get(path).then(function(response){
data = response.data
console.log(response.data) //works fine
})
return data
}
console.log(data)//returns undefined
现在如果我想用$timeout更新函数
我需要做这样的事情
$timeout(getData, 3000)
现在我怎样才能获得这些更新后的值?
编辑:
var myData = setInterval( function(){
$http.get(path).then(function(response){
return response.data['Block Devices']
})
}, 1000 );
console.log(myData)
});
返回 14 我不知道那是什么,但肯定不是正确的数据
最佳答案
使用Angular的$q,需要注入(inject)$q作为依赖,
function getData(){
var deffered = $q.defer();
var data;
$http.get(path).then(function(response){
data = response.data
$q.resolve(data);
})
return deffered.promise;
}
var getDataCall = getData();
getDataCall.then(function(data){
console.log(data);
})
如果您想重复此调用,请使用,$interval(fn,delay,[count],[invokeApply],[Pass]);
参见文档https://docs.angularjs.org/api/ng/service/$interval
尝试重复此操作,(我没有尝试过),
function getData(){
var deffered = $q.defer();
var data;
$http.get(path).then(function(response){
data = response.data
$q.resolve(data);
})
return deffered.promise;
}
$interval(function(){
getData().then(function(data){
console.log(data);
});
},3000);
关于javascript - 如何每 3 秒使用 $http.get 发出一个新请求并在函数外部获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35321467/