Last active
November 26, 2018 13:30
-
-
Save nmccready/a19370e9ae0772d03ba8 to your computer and use it in GitHub Desktop.
$http decorator to cancel requests for all $http methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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