嗨我想弄清楚如何實現新的角度攔截器,並通過刷新令牌並重試請求來處理401 unauthorized
錯誤。這是我一直遵循的指南:https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors在令牌刷新後的角度4攔截器重試請求
我成功緩存失敗的請求,並可以刷新令牌,但我無法弄清楚如何重新發送以前失敗的請求。我也想讓它與我目前使用的解析器一起工作。
token.interceptor.ts
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();
}
});
}
}
});
authentication.service.ts
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
我有同樣的問題,似乎沒有答案。 – LastTribunal