-
-
Save edysegura/9467bf8d9a379d46b578 to your computer and use it in GitHub Desktop.
[angularjs] How to create an AngularJS HTTP Interceptor
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
// 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'); | |
}); |
@gergely-kovacs It doesn't work, you need to change it to $httpProvider.interceptors.push('MyHttpInterceptor');
otherwise you get Error: [$injector:unpr] Unknown provider: LoggingHttpInterceptorProvider
.
@edysegura This is a good example, thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You create a factory with the name MyHttpInterceptor, but add it as LoggingHttpInterceptor, how does that work (sorry I have a very limited understanding of AngularJS)?