【问题标题】:Http interceptor on response not working in angular 5响应中的 Http 拦截器在角度 5 中不起作用
【发布时间】:2018-10-05 13:33:24
【问题描述】:

如果任何 api 返回 401 错误响应,我希望用户自动注销。为此,我将拦截每个请求,一旦错误代码出现 401,我将清除本地存储中的 jwt 令牌并auth guard 阻止用户跳转到该路由。但是在实现拦截器之后(示例非常少,文档中也没有提及)我无法点击任何 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)
            }
        });
    }
}

【问题讨论】:

    标签: angular5 angular-http-interceptors


    【解决方案1】:

    如果出现错误,为什么你需要跟踪每个请求,如果你只能catch需要?

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

    【讨论】:

    • 你好,能否给出catch error函数的实现?
    • import { catchError } from 'rxjs/operators/catchError';
    • 非常感谢你。虽然 Observable.throw() 已被弃用,但我使用了 ErrorObservable.create('Auth error');然后 import 语句是 import {ErrorObservable} from 'rxjs/observable/ErrorObservable';但是很有帮助哟。有人给这个人一块饼干!
    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多