0
votes

In my interceptor i want to put a pipe on response and make logout if the response statusCode is 401 but the problem is when i put a catchError the observable is not of type HttpEvent and the intercept function expects the return of that type?

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = `Agency ${this.auth.token}`;
    const requestWithHeaders = req.clone({ setHeaders: {'Content-Type': 'application/json'}});
    if (!!this.auth.token) {
        const authReq = requestWithHeaders.clone({ setHeaders: { Authorization: authToken} });
        return next.handle(authReq).pipe(
            catchError(er => {
                if (er.status === 401) {
                    this.auth.logout();
                }
                return er;
            })
        );
    } else {
        return next.handle(requestWithHeaders);
    }
}

}.

3
create a logout route and navigate.Gourav Garg

3 Answers

1
votes

Throw a new error which will be forwarded instead of just returning the error:

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators'

...

catchError(er => {
    if (er.status === 401) {
        this.auth.logout();
    }
    return throwError(er);
})
1
votes

you can handle your Error response with below approach, try this

   return next.handle(clonedRequest).do((event: HttpEvent<any>) => {}, (error: any) => {
      if (error instanceof HttpErrorResponse) {
           if (error.status == 401 || error.status == 403) {
             this.auth.logout();
         }
      }
   });

I hope this will solve your issue :)

1
votes

This is how i have done it.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //   const  newReq= req.clone({headers: req.headers.set('source', 'WEB')});
  const  newReq = req.clone({
        headers: new HttpHeaders({
            'source': 'WEB',
            'Authorization': localStorage.getItem(TOKEN) || ''
        })
    });
    return next.handle(newReq).pipe(map((e: HttpEvent<any>) => {
        if (e instanceof HttpResponse) {
    /*        console.error(e);
            console.log(e.status);*/
            if (e.status === 401) {
                throw new Error('invalid token');
            }
        }
        return e;
    }));
}

if (e instanceof HttpResponse) this me that if its response>> if its response then do validation as you like .here im just throwing error but we can clear saved tokens and redirect to login page aswell