Angular JS built in service $http is used to make http server requests. More often than not you would find yourself in a situation where you would want to run hooks for the http calls, i.e execute some logic before or after the http call. For example appending the auth token to every api request or generic http response error handling. For this $http interceptors become quite handy. One more very important use of interceptors is to log http requests made to external API’s which can be used for analytics.
Although there is not a lot written about interceptors on the documentation site, reading through the code comments makes much more sense. One way to implement interceptors is to create a service and implement the required hooks as functions in the service and then push the service to interceptors array. Or by pushing an anonymous factory(function) with the required functions to http interceptors array. There are four types of interceptors Request, Response, Request error and Response Error. Every interceptor factory should have one out of these four methods defined rest are optional.
Let’s clear things with an example.
A response interceptor function takes a promise object as argument and returns the resolved promise. The example Below handles 401 errors from the servers and does suitable error handling. If the http request returns a success response it does not do anything. But if there is a error, it checks for the error code from the server and if its 401, redirects the user to the login page.
A request interceptor function takes in a config object and returns a modified config object. In the Example Below we are going to add a ‘auth token’ parameter to every request made to the API server.
Although the examples above have implemented two different factories for simplicity, they can be combined into a single factory. And the interceptor looks like the one below.
Final Gist borrowed form https://gist.github.com/gnomeontherun/5678505