嗨,我正在尝试弄清楚如何实现新的角度拦截器并401 unauthorized
通过刷新令牌并重试请求来处理错误。这是我一直遵循的指南:https : //ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors
我已经成功地缓存了失败的请求,并且可以刷新令牌,但是我不知道如何重新发送以前失败的请求。我也想使它与我当前使用的解析器一起使用。
令牌拦截器
return next.handle( request ).do(( event: HttpEvent<any> ) => {
if ( event instanceof HttpResponse ) {
// do stuff with response if you want
}
}, ( err: any ) => {
if ( err instanceof HttpErrorResponse ) {
if ( err.status === 401 ) {
console.log( err );
this.auth.collectFailedRequest( request );
this.auth.refreshToken().subscribe( resp => {
if ( !resp ) {
console.log( "Invalid" );
} else {
this.auth.retryFailedRequests();
}
} );
}
}
} );
身份验证服务
cachedRequests: Array<HttpRequest<any>> = [];
public collectFailedRequest ( request ): void {
this.cachedRequests.push( request );
}
public retryFailedRequests (): void {
// retry the requests. this method can
// be called after the token is refreshed
this.cachedRequests.forEach( request => {
request = request.clone( {
setHeaders: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${ this.getToken() }`
}
} );
//??What to do here
} );
}
上面的retryFailedRequests()文件是我不知道的。重试后,如何重新发送请求并使它们通过解析器可用于路由?
这是所有相关的代码,如果有帮助的话:https : //gist.github.com/joshharms/00d8159900897dc5bed45757e30405f9