Angular 5 http响应拦截器无法读取状态码

Angular5 http reponse interceptor unable to read status code

我正在尝试拦截 http 响应并重定向任何 401,但下面的错误对象只返回以下字符串。我期待至少找到状态代码..

401 - Unauthorized Details: Http failure response for http://localhost:4200/api/foo: 401 Unauthorized

我可以在网络选项卡中看到服务器返回格式正确的 401。关于如何正确阅读它们的任何想法?

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authRequest = request.clone({
        setHeaders: {
            Authorization: `Bearer ${this.authService.getToken() || ''}`
        }
    });

    return next.handle(authRequest).do(event => { }, err => {
        if (err instanceof HttpErrorResponse && err.status === 401) {
            this.authService.handleAuthentication();
        }
    });
}

编辑:我刚刚注意到,如果我关闭 Web 服务器以强制 504 网关超时,我也会得到一个没有错误代码的完整字符串错误。

504 - Gateway Timeout Details: Http failure response for http://localhost:4200/api/foo: 504 Gateway Timeout

尝试使用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);
    });

通过执行以下操作,我能够使我的 Auth Interceptor 在 Angular 5 中正常运行:

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();
      }
    });
  }
}

好的,所以这里的问题是我有一个预先存在的错误拦截器,它在我的 401 拦截器之前修改响应。这家伙把一切都串起来了。感谢以上所有回复。

对于Angular6,看这个post: