Skip to content

Instantly share code, notes, and snippets.

@pinkhominid
Last active January 26, 2019 04:46
Show Gist options
  • Save pinkhominid/dcdedbe3b03c432d70f39fef4ce2c3e2 to your computer and use it in GitHub Desktop.
Save pinkhominid/dcdedbe3b03c432d70f39fef4ce2c3e2 to your computer and use it in GitHub Desktop.
AngularJS abortable GET request
/** 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