Angular5 http reponse interceptor unable to read status code

不问归期 提交于 2019-12-07 02:40:32

try to use catch

return next
    .handle(authReq)
    .do(event => {
        if (event instanceof HttpResponse) {
            /* Make your code here */
        }
    })
    .catch((err) => {
        if (err.status === 401 && err.statusText === 'Unauthorized') {


        }
        return Observable.throw(err);
    });

I was able to get my Auth Interceptor functioning correctly in Angular 5 by doing the following:

auth.interceptor.ts

import { Injectable } from '@angular/core';
import {
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor, 
    HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
      private authService: AuthService
  ) { }

  public intercept(
      req: HttpRequest<any>,
      next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    return this.authService.getToken().flatMap((token: string) => {
      return next.handle(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
    }).do(() => { }, (error: any) => {
      if (error instanceof HttpErrorResponse && (error as HttpErrorResponse).status === 401) {
        this.authService.login();
      }
    });
  }
}

Ok so the problem here was I had a pre-existing error interceptor that was modifying the response before my 401 interceptor. This guy was stringifying everything. Thanks to all the above responses.

For Angular 6, look at this post:
HttpClient Interceptor forces request duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!