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 is 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 { 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");  
	}
}

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

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.