我已经使用$timeout
每5秒调用一次有角度的JS服务。但这会导致页面或光标重新加载到我的应用程序中。谁能帮助我停止页面重新加载?
var app = angular.module('myApp', ['ngAnimate']);
app.controller('MainCtrl', function($scope, $http, $timeout) {
var loadTime = 1000, //Load the data every second
errorCount = 0, //Counter for the server errors
loadPromise; //Pointer to the promise created by the Angular $timout service
var getData = function() {
//console.log('http://httpbin.org/delay/1?now=' + Date.now());
$http.get('http://httpbin.org/delay/1?now=' + Date.now())
.then(function(res) {
$scope.data = res.data.args;
errorCount = 0;
nextLoad();
})
.catch(function(res) {
$scope.data = 'Server error';
nextLoad(++errorCount * 2 * loadTime);
});
};
var cancelNextLoad = function() {
$timeout.cancel(loadPromise);
};
var nextLoad = function(mill) {
mill = mill || loadTime;
//Always make sure the last timeout is cleared before starting a new one
cancelNextLoad();
loadPromise = $timeout(getData, mill);
};
//Start polling the data from the server
getData();
//Always clear the timeout when the view is destroyed, otherwise it will keep polling and leak memory
$scope.$on('$destroy', function() {
cancelNextLoad();
});
$scope.data = 'Loading...';
});
答案 0 :(得分:0)
在取消之前检查loadPromise
是否存在:
var cancelNextLoad = function() {
̶$̶t̶i̶m̶e̶o̶u̶t̶.̶c̶a̶n̶c̶e̶l̶(̶l̶o̶a̶d̶P̶r̶o̶m̶i̶s̶e̶)̶;̶
loadPromise && $timeout.cancel(loadPromise);
};