Skip to content

Instantly share code, notes, and snippets.

@kapusta
Forked from gnomeontherun/angularjs-interceptor.js
Last active December 21, 2015 08:58
Show Gist options
  • Save kapusta/6281611 to your computer and use it in GitHub Desktop.
Save kapusta/6281611 to your computer and use it in GitHub Desktop.
AngularJS interceptor factory with diff syntax from the gist I forked from. This logs everything out and is verbose as hell (dial that back as needed). In your module.config() you'll push 'intercept' onto the interceptors array by saying $httpProvider.interceptors.push('intercept'); The IIFE is in place because I keep all of my factories, servic…
// Adapted from: https://gist.github.com/gnomeontherun/5678505
(function(angular, document){
'use strict';
angular.module('YOURMODULENAMEHERE').factory('intercept', ['$q', function($q) {
console.log("intercept factory is running");
var i = {};
i.request = function(obj) {
// Access to lots of great stuff in here...
// obj.headers (object), obj.method (string), obj.url (string), obj.withCredentials (boolean)
console.log("intercept: request");
console.log(obj);
// transform the response here if you need to, the request config is in config
return obj || $q.when(obj);
};
i.requestError = function(obj) { // a failed request
console.log("intercept: requestError");
console.log(obj);
return $q.reject(obj);
};
i.response = function(obj) { // a succuesful response
console.log("intercept: response");
console.log(obj);
// transform the response here if you need to, the deserialize JSON is in obj.data
return obj || $q.when(obj);
};
i.responseError = function(obj) { // a failed response
console.log("intercept: responseError");
console.log(obj); // this object is handed to $http and .then() fires with the object
return $q.reject(obj);
};
return i;
}]);
}(window.angular, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment