【发布时间】: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