MOCKSTACKS
EN
Questions And Answers

More Tutorials









Angular HTTP Interceptor


Generic httpInterceptor step by step
Create an HTML file with the following content:

<!DOCTYPE html>
<html>
<head>
 <title>Angular Interceptor Sample</title>
 <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
 <script src="app.js"></script>
 <script src="appController.js"></script>
 <script src="genericInterceptor.js"></script>
</head>
<body ng-app="interceptorApp">
 <div ng-controller="appController as vm">
 <button ng-click="vm.sendRequest()">Send a request</button>
 </div>
</body>
</html>

Add a JavaScript file called 'app.js':

var interceptorApp = angular.module('interceptorApp', []);
interceptorApp.config(function($httpProvider) {
 $httpProvider.interceptors.push('genericInterceptor');
});

Add another one called 'appController.js':

(function() {
 'use strict';
 function appController($http) {
 var vm = this;
 vm.sendRequest = function(){
 $http.get('http://google.com').then(function(response){
 console.log(response);
 });
 };
 }
 angular.module('interceptorApp').controller('appController',['$http', appController]);
})();

And finally the file containing the interceptor itself 'genericInterceptor.js':

(function() {
 "use strict";
function genericInterceptor($q) {
 this.responseError = function (response) {
 return $q.reject(response);
 };
 this.requestError = function(request){
 if (canRecover(rejection)) {
 return responseOrNewPromise
 }
 return $q.reject(rejection);
 };
 this.response = function(response){
 return response;
 };
 this.request = function(config){
 return config;
 }
 }
 angular.module('interceptorApp').service('genericInterceptor', genericInterceptor);
})();


The 'genericInterceptor' cover the possible functions which we can override adding extra behavior to our application

Conclusion

In this page (written and validated by ) you learned about AngularJS HTTP Interceptor . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS Session storage.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.