import { Injectable } from '@angular/core' ; import { HttpEvent , HttpInterceptor , HttpHandler , HttpRequest } from '@angular/common/http' ; import { Observable , throwError } from 'rxjs' ; import { catchError , mergeMap , take } from 'rxjs/operators' ; import { Store } from '@ngrx/store' ; import { CoreState , authorizationHeader } from '../store' ; import { AuthenticationProvider } from './authentication.provider' ; import { Router } from '@angular/router' ; import { interceptorConstants } from '../../shared/model' ; @ Injectable ( ) export class AuthInterceptor implements HttpInterceptor { constructor ( private store , private authService , private router ) { } intercept ( req , next ) { let authHeader ; this . store . select ( authorizationHeader ) . pipe ( take ( 1 ) ) . subscribe ( ah => { authHeader = ah ; } ) ; if ( authHeader ) { let authReq = req . clone ( { headers : req . headers . set ( 'Authorization' , authHeader ) } ) ; let errorCount = 0 ; return next . handle ( authReq ) . pipe ( catchError ( ( error , caught ) => { if ( error . status === interceptorConstants . UNAUTHORIZED ) { this . authService . logout ( ) ; this . router . navigate ( [ '/dashboard' ] ) ; } if ( error . status === interceptorConstants . TOKEN_EXPIRE ) { return this . authService . refreshToken ( ) . pipe ( mergeMap ( ( tokenResponse ) => { authReq = req . clone ( { headers : req . headers . set ( 'Authorization' , 'Bearer ' + tokenResponse ) } ) ; return next . handle ( authReq ) ; } ) ) ; } console . log ( 'error------>' , error ) ; if ( error . status === interceptorConstants . INTERNAL_ERROR || error . status === interceptorConstants . GATEWAY_TIMEOUT ) { if ( errorCount < interceptorConstants . MAXIMUM_RE_REQUEST_LIMIT ) { errorCount ++ ; return next . handle ( authReq ) ; } else { this . router . navigate ( [ '/dashboard' ] ) ; } } return throwError ( error ) ; } ) ) as any ; } else { return next . handle ( req ) ; } } }