0

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;
            })
        }
    }


}    
Akif
  • 7,098
  • 7
  • 27
  • 53
Rajat Singh
  • 1
  • 1
  • 4

2 Answers2

0

Don't subscribe in interceptor, instead use following 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');
            const dupReq = request.clone({url: validateRequestUrl});
            return next.handle(dupReq).pipe(tap((event) => {
               if(event instanceof HttpResponse){
                if(event.body.auth === true) {
                   return event.body;
                } else {
                    return EMPTY;
                    this.router.navigate(['/login']);
                }
              }
            }, (error) => {
                return EMPTY;
            }));
        }
    }
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
  • Hi! Thanks for the response. But in the line dupReq.pipe(tap((event) =>{}, I am getting this error - Property 'pipe' does not exist on type 'HttpRequest'. – Rajat Singh Dec 09 '20 at 11:07
  • Could not solve my issue due to this error. Any idea how to solve this? – Rajat Singh Dec 09 '20 at 19:03
  • This code is giving the same result as subscription. After return he return statement is executed but the current API response is not coming. Any clue why this is happening? – Rajat Singh Dec 10 '20 at 10:56
0

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'.

Rajat Singh
  • 1
  • 1
  • 4