【发布时间】:2017-12-31 09:34:40
【问题描述】:
我需要(在拦截器类中)对 403 Forbidden HTTP status(获取/刷新)JWT 令牌做出反应,并使用新令牌重试请求。
在下面的代码中,当服务器返回错误响应时,它会进入成功回调(而不是像我期望的那样进入错误回调),并且事件是 typeof 对象(对错误响应的反应是无用的)。事件对象如下所示: {类型:0}。
问题:
-如何正确处理httpErrorResponse(403 Forbidden)中的 当我需要刷新accessToken并重试http请求时使用HttpInterceptor?
import {
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
class JWTInterceptor implements HttpInterceptor {
constructor(private tokenService: TokenService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let myHeaders = req.headers;
if (this.tokenService.accessToken) {
myHeaders = myHeaders.append('Authorization',`${this.tokenService.accessToken.token_type} ${this.tokenService.accessToken.access_token}`)
}
const authReq = req.clone({headers: myHeaders});
return next.handle(authReq).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// success callback
}
}, (err: any) => {
if (err instanceof HttpErrorResponse {
if (err.status === 403) {
// error callback
this.tokenService.obtainAccessToken()
}
}
})
.retry(1);
}
}
【问题讨论】:
标签: angular error-handling jwt angular-http-interceptors