-
-
Save gnomeontherun/5678505 to your computer and use it in GitHub Desktop.
// Intercepting HTTP calls with AngularJS. | |
angular.module('MyApp', []) | |
.config(function ($provide, $httpProvider) { | |
// Intercept http calls. | |
$provide.factory('MyHttpInterceptor', function ($q) { | |
return { | |
// On request success | |
request: function (config) { | |
// console.log(config); // Contains the data about the request before it is sent. | |
// Return the config or wrap it in a promise if blank. | |
return config || $q.when(config); | |
}, | |
// On request failure | |
requestError: function (rejection) { | |
// console.log(rejection); // Contains the data about the error on the request. | |
// Return the promise rejection. | |
return $q.reject(rejection); | |
}, | |
// On response success | |
response: function (response) { | |
// console.log(response); // Contains the data from the response. | |
// Return the response or promise. | |
return response || $q.when(response); | |
}, | |
// On response failture | |
responseError: function (rejection) { | |
// console.log(rejection); // Contains the data about the error. | |
// Return the promise rejection. | |
return $q.reject(rejection); | |
} | |
}; | |
}); | |
// Add the interceptor to the $httpProvider. | |
$httpProvider.interceptors.push('LoggingHttpInterceptor'); | |
}); |
@kylebuch8 was thinking the same thing :) MyHttpInterceptor instead of LoggingHttpInterceptor or perhaps changing the name in $provide.factory
The last line should be
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');
I was not aware that http interceptors exist and you can do that. This is exactly the kind of solution I've been looking for for the project I am currently working on. Thank you so much.
Nice thing about this is you can modify requests for UI router partial loading.
With token?
doesnt work , using angular 1.4
In line 29 why do we need the $q.when(response)
if it's empty?
Can confirm this doesn't seem to work in Angular 1.4.8. Which is a shame.
Does this work with iframe requests?
@vejandla: Nope. It doesn't.
Did you mean to push MyHttpInterceptor to the interceptors array instead?