【问题标题】:Long polling issues in angular角度中的长轮询问题
【发布时间】:2016-06-07 13:02:08
【问题描述】:

最近我一直在为 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();

}

这个问题在于间隔不起作用,它看起来只是一种每秒运行数千次的常规递归方法。我需要找到一个解决方案,我可以在没有重复线程的情况下对某些 url 执行长轮询。我该怎么做?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    省略括号就可以了:

    promise = $interval( $scope.longPolling, 5000);
    

    括号的意思是“正确调用这个函数”。 $interval 期望的是回调,而不是函数调用的结果。

    【讨论】:

    • 没问题,10 个 Javascript 开发人员中有 11 个曾经遇到过这个问题。
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多