终止AngularJS连接:请求阻塞导致搜索栏无响应如何解决?
AngularJS 终止HTTP请求与请求阻塞问题解决方案
终止$http请求的实现方式
AngularJS 1.x 的$http服务支持通过timeout配置项终止未完成的请求,你需要配合$q服务创建延迟对象,主动resolve该对象即可终止对应请求。
修复后的完整代码
app.controller('GenTable', ['$http', '$scope', '$window', '$q', function($http, $scope, $window, $q) { console.log("I'm called"); // 保存待终止请求的延迟对象 let pendingRequest = null; // 终止未完成请求的公共方法 function cancelPendingRequest() { if (pendingRequest) { pendingRequest.resolve('请求主动终止'); pendingRequest = null; } } $scope.CallSearch = function() { // 发起新请求前先终止上一次未完成的请求 cancelPendingRequest(); pendingRequest = $q.defer(); if ($scope.SearchField == null) { $http.get("https://localhost:(portnumberhere)/project/all", { timeout: pendingRequest.promise }).then(function(response) { $window.Project = response.data; const ProjectLength = $window.Project.length; console.log("I'm in get"); pendingRequest = null; }).catch(function(err) { console.log('请求失败:', err); pendingRequest = null; }); } else { const PostData = $scope.SearchField; $http.post("https://localhost:(portnumberhere)/project/filter", PostData, { timeout: pendingRequest.promise }).then(function(response) { $window.Project = response.data; const ProjectLength = $window.Project.length; console.log("I'm in post with" + PostData); pendingRequest = null; }).catch(function(err) { console.log('请求失败:', err); pendingRequest = null; }); console.log("I'm not in post with PostData as " + PostData); } } // 初始化请求也添加终止逻辑 cancelPendingRequest(); pendingRequest = $q.defer(); $http.get("https://localhost:(portnumberhere)/project/all", { timeout: pendingRequest.promise }).then(function(response) { $window.Project = response.data; $scope.Project = $window.Project; const ProjectLength = $window.Project.length; console.log("I'm in get table"); pendingRequest = null; }).catch(function(err) { console.log('初始化请求失败:', err); pendingRequest = null; }); console.log("I'm at end"); }]);
核心修改说明
- 新增
$q依赖,创建延迟对象控制请求终止,每次发起新请求前主动终止未完成的旧请求,避免并发请求阻塞 - 所有
$http请求添加timeout配置,绑定对应延迟对象的promise - 修正原代码中未声明
PostData、ProjectLength变量导致的全局污染问题,避免作用域混乱触发逻辑异常 - 新增请求异常捕获逻辑,便于排查请求失败类问题
- 修正直接调用未声明的
Project变量的问题,统一从$window.Project取值,避免变量未定义报错
内容的提问来源于stack exchange,提问作者user199135
相关产品推荐
相关产品推荐

