Last active
January 26, 2019 04:46
-
-
Save pinkhominid/dcdedbe3b03c432d70f39fef4ce2c3e2 to your computer and use it in GitHub Desktop.
AngularJS abortable GET request
This file contains 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
/** Aborting $http made simple */ | |
export class AbortableHttpService { | |
constructor($q, $http, $timeout) { | |
this.$q = $q; | |
this.$timeout = $timeout; | |
this.$http = $http; | |
} | |
get(url, options = {}) { | |
const {$q, $http, $timeout} = this; | |
const canceler = $q.defer(); | |
const req = $http.get(url, { ...options, timeout: canceler.promise }) | |
// log aborted request | |
.catch(res => { | |
if (res.xhrStatus === 'abort') { | |
console.log('Aborted GET', url); | |
} | |
}); | |
if (!isNaN(options.timeout)) { | |
const timer = $timeout(canceler.resolve, options.timeout); | |
req.finally(() => $timeout.cancel(timer)); | |
} | |
req.abort = canceler.resolve; | |
return req; | |
} | |
} | |
AbortableHttpService.$inject = ['$q', '$http', '$timeout']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment