Daniel Edholm Ignat
Daniel Edholm Ignat

Reputation: 268

Cancelling angular $http.jsonp results in javascript error

I'm using Angular version 1.2.1 and I'm attempting to implement cancelation in my application when a new request of the same type is initialized. I used the code examples here but I couldn't get it to work. I think this is due to the fact that I am using $http.jsonp().

When I cancel a jsonp request the .then callbacks are never called (as expected) but the request is not cancelled and when the response comes I get an undefined error in the console (the jsonp callback function no longer exists).

How do I avoid getting this console error? Is it possible to cancel a jsonp request 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');
        };
    };
}

Upvotes: 2

Views: 491

Answers (1)

Daniel Edholm Ignat
Daniel Edholm Ignat

Reputation: 268

I tried upgrading angularjs to version 1.2.27 (I should have tried that first!) and the issue was no longer there. After a bit of digging on GitHub I found the fix. Fixed since version 1.2.8

https://github.com/angular/angular.js/commit/95e1b2d6121b4e26cf87dcf6746a7b8cb4c25e7f

fix($httpBackend): cancelled JSONP requests will not print error in the console

When you cancel a JSONP request, angular deletes the callback for it. However the script still executes, and since the callback is now deleted and undefined, the script throws an exception visible in the console. The quick fix for this is not to delete the callback, but replace it with angular.noop.

Closes #5615

Closes #5616

The change that fixes the issue:

-        delete callbacks[callbackId];
+        callbacks[callbackId] = angular.noop;

Upvotes: 1

Related Questions