0
最近我一直在使用angularJS中的長輪詢。我有這個代碼在過去工作:長角度輪詢問題
function longPulling(){
$.ajax({
type: "GET",
url: "someScript.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
appendMessage("new", data);
setTimeout(
longPulling,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
appendMessage("error", textStatus + " (" + errorThrown + ")");
setTimeout(
longPulling,
15000);
}
});
};
$(document).ready(function(){
longPulling();
});
而這個工作時,我使用了一些PHP腳本。接下來,我想這在角工作,我創建了以下內容:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
}, function errorCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
});
};
$scope.longPolling();
}
出於測試目的,我不包括URL和檢查控制檯404錯誤。我用$ interval設置了5秒的時間間隔,這個問題是它創建了多個運行間隔的線程(看起來像它,糾正我,如果我錯了)。所以,我瀏覽了一些StackOverflow的主題和嘗試應用的解決方案之一,以我的代碼,看起來像這樣:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
var promise;
$scope.start = function() {
$scope.stop();
promise = $interval($scope.longPolling(), 5000);
};
$scope.stop = function() {
$interval.cancel(promise);
};
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.start();
}, function errorCallback(response) {
$scope.start();
});
};
$scope.start();
}
與這一個問題是,區間是行不通的,它lookes喜歡它只是一個定期遞歸方法,每秒運行數千次。我需要找到一個解決方案,我可以在沒有重複線程的情況下對一些URL執行長輪詢。我怎樣才能做到這一點?
謝謝,我不知道它的工作方式。 –
沒問題,10個Javascript開發人員中有11個曾經遇到這個問題。 –