The first time I discovered Angular's http interceptors it felt like a holiday. If you're unfamiliar with them, they are basically just factories that function exactly like they are named. Every request (or response) that passes through Angular's $http service first gets intercepted, allowing you to muck about with it before sending it on it's way. Here's a basic shell of one:
Once it's built, you need to register it with $httpProvider. Like so:
One pretty handy use for these would be to manage your users' logged in state. Stuff an auth token into the header with every request and, redirect them to the login screen if their session expires. Let's take a look at a quick and easy way to do that.
First we'll need a service to tell us if we're currently authenticated as well as give us our auth token when we ask for it.
Let's make a few assumptions for how this should flow.
Our login screen will call this service to save the token once a successful login has occurred
Our tokens will contain a couple of properties like 'issued' and 'expires_in' that we'll use those to guesstimate if our token has expired
We'll just use Angular's $sessionStorage to hang on to the tokens.
Now we can use this in our interceptor.
Notice, in the 'request' we go get our token and sneak it into the authorization header. If we get a response error, we check to see if it was a 401. If so, confirm the token expiration and either pass the error back to $http or redirect our user to the login screen.
This is just a simple example of what can be done with an interceptor. I encourage you to use your imagination and think up clever ways to use this powerful little tool in your own Angular toolbox.