1

I have an Angular template. In the app.js I have this config:

app.config(function ($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');

$routeProvider
.when('/', { .....etc

The AuthInterceptor is this factory:

'use strict';

app.factory('AuthInterceptor', function ($rootScope, $q, $window, $location) {
return {
  request: function (config) {
    config.headers = config.headers || {};
    if ($window.localStorage.token) {
      config.headers.Authorization = 'Token ' + $window.localStorage.token;
    }
    return config;
  },

  responseError: function (response) {
    if (response.status === 401) {
      $window.localStorage.removeItem('token');
      $window.localStorage.removeItem('email');
      $location.path('/');
      return;
    }
    return $q.reject(response);
  }
};
});

What does it exactly do?

1
  • Add Authorization header that contains a token. Token is stored in localStorage and remove when 401 is return by server. Commented Apr 15, 2016 at 8:11

2 Answers 2

3

Interceptors in Angular, as the name suggests, is a simple way provided by the framework to intercept and modify the application’s http requests globally before they are sent to the server. That really comes in handy, allowing us to configure authentication tokens, add logs of the requests, add custom headers that out application may need and much more.

Interceptors can perform a variety of implicit tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response. Without interception, developers would have to implement these tasks explicitly for each HttpClient method call.

@Injectable()
    export class RequestLogInterceptor implements HttpInterceptor {
      intercept(
        request: HttpRequest<any>, next: HttpHandler
      ) : Observable<HttpEvent<any>> {
        console.log(request.url);
        return next.handle(request);
      }
    }

The intercept method transforms each request into Observables, which later are going to be resolved by calling next.handle(). So, for our implementation it is quite simple: you take the request, log its url and call next.handle() to send it to the server without making any changes to it.

Sign up to request clarification or add additional context in comments.

Comments

1

The "AuthInterceptor" will inject a Token in headers.Authorization parameter for every request before it. That will allow you to keep logedIn on server side, or check if token exist and allow to some rests function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.