Created
January 8, 2016 20:19
-
-
Save arleyhr/d02a105bebac03d8ced6 to your computer and use it in GitHub Desktop.
Angular cancelable http requests
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
(function(){ | |
angular | |
.module('cancelableHttp') | |
.config(config) | |
.service('CancelableHttpService', httpService) | |
.factory('CancelableHttpInterceptor', httpInterceptor) | |
function config ($httpProvider) { | |
$httpProvider.interceptors.push('CancelableHttpService'); | |
} | |
function httpService ($q) { | |
var cancelablePromises = [], CancelableHttpService = {}; | |
CancelableHttpService.cancelablePromise = function () { | |
var cancelablePromise = $q.defer(); | |
cancelablePromises.push(cancelablePromise); | |
return cancelablePromise.promise; | |
}; | |
CancelableHttpService.cancelAll = function () { | |
angular.forEach(cancelablePromises, function (cancelPromise) { | |
cancelPromise.resolve(); | |
}); | |
cancelablePromises = []; | |
}; | |
return CancelableHttpService; | |
}; | |
function httpInterceptor ($q, CancelableHttpService) { | |
return { | |
request: function (config) { | |
if (config && config.timeout === undefined) | |
config.timeout = CancelableHttpService.cancelablePromise(); | |
return config; | |
} | |
}; | |
}; | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inject CancelableHttpService
For example when route start change: