我是app和angular的新人。
我的应用使用间隔来刷新范围,并向服务器发送get请求。我想在应用程序进入后台时取消该间隔。
我在其他帖子'$ onunload = function()'上看到了,但我不确定它是好还是如何使用它...我尝试:$scope.$onunload=function(){
// Make sure that the interval is destroyed when leaving app
$scope.stopRefresh();
};
但它不起作用。
请注意,stopRefresh()函数适用于离开选项卡,它取消间隔...
另一方面,有什么方法可以重新开始从背景回来的间隔?
这里是完整的控制器:
angular.module('starter.controllers', [])
main.controller("temperatureCtrl", ["$scope", "$rootScope", "$window", "$interval", "ArduinoService", function($scope, $rootScope, $window, $interval, service) {
$rootScope.arduinoServerUrl = '';
$rootScope.arduinoServerUrl = $window.localStorage['serverUrl'];
var autoRefresh;
$scope.channels = [];
function onTabSelected() {
$rootScope.arduinoServerUrl = $window.localStorage['serverUrl'];
}
$scope.options = {
loop: false,
//effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh() {
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) { //get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
//startRefresh()
}
$scope.stopRefresh = function() {
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$ionicView.leave', function() {
// Make sure that the interval is destroyed when leaving tab
$scope.stopRefresh();
});
$scope.$onunload=function(){
// Make sure that the interval is destroyed when leaving app
$scope.stopRefresh();
};
$scope.$on('$ionicView.enter', function() {
//star or restart interval scope update
$scope.restartRefresh();
});
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);
答案 0 :(得分:0)
我需要在angularjs'service'或'factory'中创建一些单例类。就像我在我的代码中所做的那样,你只需在恢复事件激发时取消$ inerval。
factory('BackgroundCheck', function($ionicPlatform){
var service = {};
var inBackground = false;
$ionicPlatform.ready(function() {
document.addEventListener("resume", function(){inBackground = false;}, false);
document.addEventListener("pause", function(){inBackground = true;}, false);
});
service.isActive = function(){
return inBackground == false;
}
return service;
})
我希望这对你有用。
...谢谢