嗨,我试图找出如何实现新的角度拦截器和处理 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
} );
}
上面的 retryFailedRequest ()文件是我无法解决的问题。如何重新发送请求,并在重试后通过解析器将其提供给路由?
如果有帮助的话,这是所有相关代码: https://gist.github.com/joshharms/00d8159900897dc5bed45757e30405f9