DEV Community

process20
process20

Posted on

Implementing the interceptors

Hi,
I have a problem with interceptors, now I'm learning JWT reaching the step dealing with interceptors, I'm not able to know the source of the issue, the interceptor is getting block the login API to be consumed and generate the token that will be injected in request header in the interceptor; here the code of the interceptor class:

import { catchError } from 'rxjs/operators';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from "@angular/router";
import { Observable, throwError } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(){}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
      console.log("you are in interceptor");
      // get the token from the local storage
      const token = localStorage.getItem('token');
      if(token){
        console.log("token stored to the local store: "+token);
        // modify the request header
        req = req.clone({
          setHeaders: {Authorization: `${token}`}
        });
        // handling errors
        return next.handle(req).pipe(catchError(err=>{
          console.log("something wrong in interceptor");
          if(err instanceof HttpErrorResponse){
             console.log(err.status + ': token expired, login again');
          }
          return throwError(()=> new Error('Some Unknown Error'));
        }));
      }
      else console.log("token not provided");

}
Enter fullscreen mode Exit fullscreen mode

}

if you would like the full code using Node.js and angular, here is the link on angular: https://github.com/process20/JWT-Implementation.
Hope you to help me fixing this issue, I'm struggling for more than 10 days.

Top comments (0)