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

August 17, 2018

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.

Now we need to push the interceptor to the http provider using the following code

 

Now we need to create our loader.For that we use directives

Now we have to use $broadcast and $on to display and hide the loader

$broadcast

It dispatches an event name downwards to all child scopes and notify to the registered $rootscope.scope listeners. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events . It can catch the event dispatched by $broadcast.

Now we need to add listeners to the above created directive broadcast it from the interceptor

To show the loader,inside the interceptor we add the following code

and inside the directive

 

The whole code looks like this.

Interceptor factory

directive

HTML

CSS

This code gives you a basic idea on how to create interceptor in angular 1.6.You can modify this code to do any kind of modifications while sending or recieving http requests.For more read the official documentation

https://docs.angularjs.org/api/ng/service/$http

 

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *