Skip to content

Instantly share code, notes, and snippets.

@arleyhr
Created January 8, 2016 20:19
Show Gist options
  • Save arleyhr/d02a105bebac03d8ced6 to your computer and use it in GitHub Desktop.
Save arleyhr/d02a105bebac03d8ced6 to your computer and use it in GitHub Desktop.
Angular cancelable http requests
(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;
}
};
};
})()
@arleyhr
Copy link
Author

arleyhr commented Feb 10, 2016

  1. Inject CancelableHttpService

  2. For example when route start change:

    $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    
    ...
    if (toState != fromState)
      CancelableHttpService.cancelAll()
    ...
    
    })
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment