Skip to content

Instantly share code, notes, and snippets.

@nmccready
Last active November 26, 2018 13:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmccready/a19370e9ae0772d03ba8 to your computer and use it in GitHub Desktop.
Save nmccready/a19370e9ae0772d03ba8 to your computer and use it in GitHub Desktop.
$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 data.data (less annoying)
promise.cancel = ->
canceller.resolve()
promise.catch ->
#if $q.all rejects a collection of promises then we can cancel the http
promise.cancel()
promise.finally ->
#cleanup
promise.cancel = angular.noop
canceller = promise = null
promise
#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
$delegate
]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment