Skip to content

Instantly share code, notes, and snippets.

Last active November 26, 2018 13:30
What would you like to do?
$http decorator to cancel requests for all $http methods
app.config([ '$provide', ($provide) ->
# attempting to create a cancelable $http on all its functions
$provide.decorator '$http', [ '$delegate', '$q', ($delegate, $q) ->
http = {}
methods = ['get', 'delete', 'head', 'jsonp']
dataMethods = ['post', 'put', 'patch']
allMethods = methods.concat(dataMethods)
allMethods.forEach (m) ->
http[m] = $delegate[m]
http.root = $delegate
$delegate = (requestConfig) ->
canceller = $q.defer()
angular.extend requestConfig, timeout: canceller.promise
promise = http.root(requestConfig)
#TODO: could override promise with another to return data instead (less annoying)
promise.cancel = ->
promise.catch ->
#if $q.all rejects a collection of promises then we can cancel the http
promise.finally ->
promise.cancel = angular.noop
canceller = promise = null
#pretty much straight copy paste from angular
methods.forEach (name) ->
$delegate[name] = (url, config) ->
$delegate angular.extend config or {},
method: name
url: url
dataMethods.forEach (name) ->
$delegate[name] = (url, data, config) ->
$delegate angular.extend config or {},
method: name
url: url
data: data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment