响应中的 HTTP 拦截器在 Angular 5 中不起作用

Aks*_*hay 5 angular-http-interceptors angular5

我希望如果任何 api 返回 401 错误响应,用户就会自动注销。为此,我拦截每个请求,一旦错误代码出现 401,我就会清除本地存储中的 jwt 令牌,并且身份验证防护会阻止但是在实现拦截器之后(这方面的示例非常少,并且文档中也没有提及),我无法命中任何 HTTP 请求。下面是我的代码。提前致谢。

import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

    constructor() {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).do((event: HttpEvent<any>) => {
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                // do error handling here
                console.log('and the error is ');
                console.log(err)
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

un.*_*ike 2

如果出现错误,如果您只能捕获所需的内容,为什么还需要跟踪每个请求?

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
        catchError((err:string, caught:Observable<any>)=>this.handleHttpClientError(err, caught))
    );
}

handleHttpClientError(error: any, caught: Observable<any>)
{
    if(error.status == 401){
        ... your logic here ... 
    }
    return new EmptyObservable<Response>();
    // or return Observable.throw('Auth error');
}
Run Code Online (Sandbox Code Playgroud)