How to cancel request in Http Interceptor in angular5?

1.4k views Asked by At

My angular app have a component called 'listdata.component.ts'.In ngOnInit() of this component there happens 2 api calls. But when 401 response got for the 2 requests a logout api call takes place 2 times. My interceptor code

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    notificationItem: any;
    constructor(public authService: AuthGuardService, private router: Router, private notification: NotificationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.authService.tokenValid()) {
            const authReq = request.clone({ headers: request.headers.set("Authorization", 'Bearer ' + this.authService.getToken()) });
            return next.handle(authReq).do((event: HttpEvent<any>) => {
            }, err => {

                if (err instanceof HttpErrorResponse) {

                    if (err.status === 401) {

                        if(authReq.url.indexOf('/logout') > -1){
                            localStorage.clear();
                            this.router.navigate(['login']);
                        }
                        else
                        {

                this.authService.logout()

                        }
                    }
                }
            });
        }
        else{
            return next.handle(request);
        }
    }
}

I want to cancel all the 401 requests after one 401 response and call logout for one time only.If takeUntil() operator can solve my issue?.Thanks in advance.

0

There are 0 answers