user3673265
user3673265

Reputation: 11

angularjs breaking http long pooling post request

I'm doing http post long pooling request. I want to cancel that request when stopping the service. My code looks like this:

app.service("ContactsService", function($http, $rootScope, $timeout, $q, ContactsFactory) {
  var requestCanceler = $q.defer();

  this.startHttpRequest = function(userId) {
      var httpRequest = $http.post($rootScope.base_url + '/contacts/req', { toId: userId }, timeout: requestCanceler.promise});

 httpRequest.success(function(data){
      console.log("success");
    });
    httpRequest.error(function(data, status){
      console.log("error");
    });
      }

  this.stopService = function(){
    console.log("stop contacts service");
    requestCanceler.resolve("request canceled");
  } 

}

when I'm stopping the service my application is hanging, it's because I do requestCanceler.resolve; When I change it to .reject its not hanging but the http post request is still pending.

How I can break the post request?

Thanks.

Upvotes: 0

Views: 426

Answers (1)

Steve Klösters
Steve Klösters

Reputation: 9457

The AngularJS documentation states that the promise has to be resolved for AngularJS to cancel the request:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

This can also be seen in the source, the error/reject callback is not set:

timeout.then(timeoutRequest);

The request cancelling on a rejected promise is not supported.

Upvotes: 2

Related Questions