也许这个问题已经被问过了,但我搜索并尝试了整个下午的大部分时间都没有成功,所以我真的希望有人能帮助我解决这个问题。
我希望能够每隔几秒更新我在工厂服务中设置的 $http.get() - 我的数据。
我在我的代码中添加了一些注释,还留下了一些旧东西让你们看看我尝试了什么。 (旧东西也注释掉了)
我的代码:
ovwid.factory('recentClients', [
'$http',
'$rootScope',
function ($http, $rootScope) {
var apiURL = '/plugins/data/get_client.php';
var promise;
var recentClients =
{
async: function()
{
if ( !promise )
{
// $http returns a promise, which has a 'then' function, which also returns a promise
promise =
$http.get(apiURL)
.then(function (response) {
// The then function here is an opportunity to modify the response
// The return value gets picked up by the then in the controller.
return response.data;
});
}
// Return a promise to the controller
return promise;
}
}
return recentClients;
}]);
ovwid.controller(‘client’Ctrl, [
'$scope',
'recentClients',
'$interval',
function ($scope, recentClients, $interval) {
$scope.loading = true;
function reloadData() {
// a call to the async method
recentClients().async().then(function(data) {
// console.log(data);
$scope.loading = false;
$scope.client = data;
});
}
// Initizialize function
reloadData();
// Start Interval
var timerData =
$interval(function () {
reloadData();
}, 1000);
// function myIntervalFunction() {
// var cancelRefresh = $timeout(function myFunction() {
// reloadData();
// console.log('data refres')
// cancelRefresh = $timeout(myFunction, 5000);
// },5000);
// };
// myIntervalFunction();
// $scope.$on('$destroy', function(e) {
// $timeout.cancel(cancelRefresh);
// });
}]); // [/controller]
最佳答案
我看到了几个问题。
首先:
if ( !promise )
只会在第一次返回 true。您正在将其分配给 $http
调用。
其次:
您永远不会访问工厂中的 async
方法。
您需要从工厂返回它 return recentClients.async
或从作用域调用它 recentClients.async().then(..
关于javascript - Angular : Update data every few seconds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956641/