我正在使用Angular 1.2.1版,当我初始化相同类型的新请求时,我正试图在我的应用程序中实现取消。我使用了代码示例here,但我无法让它工作。我认为这是因为我使用的是$ http.jsonp()。
当我取消jsonp请求时,永远不会调用.then回调(如预期的那样),但是请求没有被取消,当响应到来时,我在控制台中得到一个未定义的错误(jsonp回调函数不再存在)。 / p>
如何避免出现此控制台错误?是否可以取消jsonp请求alltogheter?
http://jsfiddle.net/HB7LU/8668/
HTML:
<div ng-controller="MyCtrl">
<span ng-bind="status"></span>
<hr>
<a href ng-click="doStuff()">
Start
</a>
<hr>
<a href ng-click="cancel()">
Cancel
</a>
</div>
JS:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $q, $http) {
$scope.status = "Idle";
$scope.doStuff = function() {
var canceller = $q.defer();
$scope.status = "Ongoing";
$scope.getting = $http.jsonp('http://cruisebookingapi.ving.se/cruisePackage/search/1/STO/141220/false/20141211/42,42/-1?callback=JSON_CALLBACK', {timeout: canceller.promise});
$scope.getting.then(function(data) {
$scope.status = "Finished";
console.log(data);
});
$scope.cancel = function() {
$scope.status = "Cancelled";
canceller.resolve('Cancel all the things');
};
};
}
答案 0 :(得分:1)
我尝试将angularjs升级到版本1.2.27(我应该先尝试一下!)然后问题就不再存在了。在对GitHub进行了一些挖掘后,我找到了修复程序。 自版本1.2.8起修复
https://github.com/angular/angular.js/commit/95e1b2d6121b4e26cf87dcf6746a7b8cb4c25e7f
fix($ httpBackend):取消JSONP请求不会在控制台中打印错误
当您取消JSONP请求时,angular会删除它的回调。但是,脚本仍然会执行,并且由于回调现在已被删除且未定义,因此脚本会在控制台中显示异常。对此的快速解决方法不是删除回调,而是将其替换为
angular.noop
。关闭#5615
关闭#5616
解决问题的更改:
- delete callbacks[callbackId];
+ callbacks[callbackId] = angular.noop;