如何让这个响应拦截器在Angular中工作?

问题描述 投票:0回答:1

我有一个HttpInterceptor的以下代码,但我不能让它的响应拦截器部分工作:

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

  }
}

它处理响应的部分无效。基本上我试图检查401是否返回,然后如果有401则自动将用户注销。

angular response angular-http-interceptors
1个回答
1
投票

你需要使用catch来专门捕获错误响应。

RxJS 5及以下(或安装了rxjs-compact的RxJS 6+兼容性):

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

没有rxjs-compact的RxJS 6+:

catch被删除,因为它是JS中的保留关键字。

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

或者,如果你仍想使用pipetaptap有三个可选参数:next callback,error callback和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');
      }
    }
  ));
© www.soinside.com 2019 - 2024. All rights reserved.