angularangular-httpclientangular-http-interceptors

Calling another API in Angular 10 interceptor is blocking the current API request


I am calling an API to validate the token in the interceptor and when I get the response of the API call in the interceptor, I am returning next.handle(request). But the current API is not giving a response after that. Can somebody please explain why after I get the success response from the validate token service the actual API being currently called is not giving the response?

Here is my code:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse, HttpResponse } from 
'@angular/common/http';
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { EMPTY, throwError } from 'rxjs';
import { RestServiceService } from 'src/app/services/rest-service.service';
import { AppConfig } from 'src/app/config/app.staticValues';
import { LoginService } from '../services/login.service';
import { Router } from '@angular/router';

@Injectable()
export class TokenAuthInterceptor implements HttpInterceptor {
    public count = 0;
    constructor(private restService: RestServiceService, private loginService: LoginService, public  
router: Router) { }

    intercept(request: HttpRequest<any>, next: HttpHandler) {
        // console.log('inside auth interceptor');
        if (request.url.includes('jwt')) {
            return next.handle(request)
            .pipe(
                tap(
                    (event) =>{
                        if(event instanceof HttpResponse){
                            console.log(event);
                                                   

                        }
                    },
                    (error: HttpErrorResponse) =>{
                        console.log(error);
                        this.router.navigate(['/login']);
                    }        
                )
            )
        }
        else if (request.url.startsWith('http')) {
            const validateRequestUrl = AppConfig.HOST_NAME + AppConfig.AUTHENTICATION.validateToken;
            const token = this.sessionStorage.get('token');

            this.restService.validateToken(validateRequestUrl, token).subscribe((data) => {
                if(data.auth === true) {
                    return next.handle(request);
                } else {
                    return EMPTY;
                    this.router.navigate(['/login']);
                }
            }, (error) => {
                return EMPTY;
            })
        }
    }


}    

Solution

  • The above solution did not seem to work for me. Actually, I did not need to subscribe() inside the interceptor, instead return an Observable<HttpEvent>, which can be done by tap and switch map. Found my solution in this link Angular HTTP Interceptor subscribing to observable and then returning next.handle but throwing TypeError: You provided 'undefined'.