Tuan-Anh Tran

Cancelling $http request in AngularJS

Posted on June 26, 2015  •  1 minutes  • 98 words

It’s as simple as this. Basically you return a promise (canceller) and let those who call your service ability to cancel via canceller.resolve('reason goes here'). Alternatively, you can provide a function cancel which does the same as canceller.resolve() if you don’t want to expose the canceller promise.

.service('MyService', function($http, $q) {

  this.canceller = $q.defer()

  this.my_func = function(params) {
    params.timeout = canceller.promise
    return {
      promise: $http.get(url, params),
      canceller: canceller      
    }
  }

})

To verify if your code is working as expected, you can check in Network tab in Developer Tools. The request will be marked with status as cancelled.

Follow me

Here's where I hang out in social media