Search code examples
angularhttpinterceptorangular-http-interceptors

How to call another (Refresh Token) API in Angular Interceptor?


I wanted to fetch new access token before making api request. This token will append to previous api call in interceptor. So how to make another api call in angular interceptor?

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// To do for validating token 
    request = request.clone({
        setHeaders: {
            Authorization: 'Bearer '+ localStorage.getItem('access_token')
        }
    });
    return next.handle(request);
  }
}

Solution

  • Angular interceptor provides a way to call another api call before making actual api call. Before proceeding further you need to import following

    import { HttpClient } from '@angular/common/http';
    import { catchError, switchMap, tap } from 'rxjs/operators';
    

    In above tap is being used to get response of intermediate call where as switchMap is used for calling actual api call.

    So, it has following steps to do job.

    1. you need to intercept actual api call
    2. make http get api call for fetching new access token
    3. parse response of above api access token in local variable or store in localstorage
    4. clone actual api call request with latest access token
    5. return the request

    so, the code would look like below.

     constructor(private http: HttpClient) {}
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return this.http.get(`https://<fetch access token URL>`, {observe: 'response'}).pipe(
          tap(response => {
            localStorage.setItem("access_token", response.headers.get('access_token'));
          }),
          switchMap(() => {
            request = request.clone({
              setHeaders: {
                Authorization: `Bearer ${localStorage.getItem('access_token')}`
              }
            });
            return next.handle(request);
          })
        );
    });