首页 > 解决方案 > 如果有 401 响应,角度拦截器会注销应用程序吗?

问题描述

在我的拦截器中,如果响应 statusCode 为 401,我想在响应上放置一个管道并注销,但问题是当我放置一个 catchError 时,observable 不是 HttpEvent 类型并且拦截函数期望返回该类型?

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = `Agency ${this.auth.token}`;
    const requestWithHeaders = req.clone({ setHeaders: {'Content-Type': 'application/json'}});
    if (!!this.auth.token) {
        const authReq = requestWithHeaders.clone({ setHeaders: { Authorization: authToken} });
        return next.handle(authReq).pipe(
            catchError(er => {
                if (er.status === 401) {
                    this.auth.logout();
                }
                return er;
            })
        );
    } else {
        return next.handle(requestWithHeaders);
    }
}

}。

标签: angulartypescriptangular-http-interceptors

解决方案


抛出一个新的错误,它将被转发而不是仅仅返回错误:

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators'

...

catchError(er => {
    if (er.status === 401) {
        this.auth.logout();
    }
    return throwError(er);
})

推荐阅读