Http interceptor in AngularJS : adding tokens and loading image to every http request

While creating AngularJS applications,we might need to send multiple  http requests to backend apis to fetch the data that need to be populated within our HTML.In most cases, these backend apis might be protected using token .Also we might need to add a loading image to indicate the user that the data is being fetched. HttpInterceptor helps us to a display the loader image before and hide the loader image after completing the request  and also add token to every request header.This tutorial helps us to create an HttpInterceptor in AngulaJS. We create an  app using the following code

Now we create a factory which will intercept http requests.Inside the interceptor we use a variable httpRequestNumber,which tracks the number of requests.When a new request comes up we increment it httpRequestNumber++ and on response or error we decrement it httpRequestNumber– .We also inject $q and $rootScope.$q is service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.$rootScope is the root scope .every app has single root scope. All other scopes are descendant scopes of the root scope.We also add a token to the request header using the following code.

The interceptor factory will look like this….

Share this page in social media platforms