使用拦截器无法捕获HTTP错误代码

时间:2019-12-12 20:10:55

标签: angular http interceptor

我正在尝试使用拦截器来捕获所有401错误并将用户踢出会话,但是我只能通过检查每个查询来捕获它

这有效:

服务:

const httpOptions: { headers; observe; } = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
    observe: 'response'
};

createSomething(something: Something): Observable<HttpEvent<Something>> {

    return this.http.post<Something>(this.urlSomething, something, httpOptions)
}

组件

this.somethingService.createSomething(incomingSomething).subscribe(
    res => {
        result = res;

        if (result.status == 401) {

            setTimeout(() => {
                this.authenticationService.logout();
                location.reload(true);
            }, 1000);

        return;
    }
);

但是,如果我尝试使用拦截器无法捕获错误,可能是什么问题?

拦截器:

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

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

        return next.handle(request).pipe(catchError(err => {

            if (err.status === 401) {

                setTimeout(() => {
                    this.authenticationService.logout();
                    location.reload(true);
                }, 1000);
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
}

0 个答案:

没有答案