CaptainDriftwood
CaptainDriftwood

Reputation: 5708

How do I get this response interceptor to work in Angular?

I have the following code for an HttpInterceptor but I can't get the response interceptor part of it to work:

import { Injectable } from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from './user.service';
import { tap, map } from 'rxjs/operators';


@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
  constructor(private user: UserService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!localStorage.getItem('token')) {
      const modified = req.clone();
      return next.handle(modified)
        .pipe(
          tap(event => {
            if (event instanceof HttpErrorResponse) {
              if (event.status === 401) {
                this.user.logout();
              }
            }
          })
        );
    } else {
      const modified = req.clone({setHeaders: {'Authorization': 'JWT ' + localStorage.getItem('token')}});
      return next.handle(modified)
        .pipe(
          tap(event => {
            if (event instanceof HttpErrorResponse) {
              if (event.status === 401) {
                this.user.logout();
              }
            }
          })
        );
    }

  }
}

The part where it is handling the response isn't working. Basically I am trying to check if a 401 was returned and then log the user out automatically if there was a 401.

Upvotes: 0

Views: 2420

Answers (1)

Jasmonate
Jasmonate

Reputation: 752

You'll need to use catch to specifically catch the error response.

RxJS 5 and below (or RxJS 6+ with rxjs-compact installed for compatibility):

next.handle(modified).catch(errorResponse => { 
  // do something
})

RxJS 6+ without rxjs-compact:

catch was removed because it is a reserved keyword in JS.

next.handle(modified).pipe(
  catchError(errorResponse => { 
  // do something
  }))

Or, if you still want to use pipe and tap, tap has three optional parameters: next callback, error callback and complete callback.

next.handle(modified).pipe(
  tap(
    event => { 
      if (event instanceof HttpResponse)
        console.log('request succeeded');
    },
    error => {
      if (error instanceof HttpErrorResponse) {
        console.log('request failed');
      }
    }
  ));

Upvotes: 1

Related Questions