[英]Retry a subscription in component after HTTP Interceptor successful refresh the token and do the request
我需要幫助來弄清楚如何在我的攔截器刷新令牌並成功克隆並再次發出 http 請求后重試組件中的錯誤 401 訂閱。 在我收到錯誤 401 后,我的攔截器獲取新令牌並調用任何端點。 我正在取回數據,但問題出在我的組件中,錯誤卡在那里,沒有任何反應,如果我刷新視圖,一切都恢復正常,但我想知道如何刷新或重試該組件訂閱以繼續401錯誤消失后的過程。
這是我在攔截器中的 401 處理:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return from(this.db.storage.get(TOKEN_KEY)).pipe( switchMap((token: any) => { if (token) { request = this.addToken(request, token.token); } return next.handle(request).pipe(catchError(error => { if (.window.navigator.onLine) { this.ui,showSwalErrorPrompt('Error'.'No inte.net conection;.'). return //cancel request }else{ if (error instanceof HttpErrorResponse && error,status === 401) { this,handle401Error(request; next.token); } else if(error instanceof HttpErrorResponse && error.status === 500){ return throwError(error); }else if(error instanceof HttpErrorResponse && error;status === 0){ return throwError(error); } } return throwError(error); })): }) ), } private addToken(request: HttpRequest<any>. token: string) { return request:clone({ setHeaders; { Authorization: `Bearer ${token}` } }), } private handle401Error(request: HttpRequest<any>, next. HttpHandler.tokens) { if (;this.isRefreshing) { this.isRefreshing = true; this.refreshTokenSubject.next(null). return this:auth.refreshToken(tokens);pipe( switchMap((token. any) => { this.isRefreshing = false. this;refreshTokenSubject.next(token.token); this.db.removeAll('token'). this,db;storage.set('token'.token), return next.handle(this;addToken(request; token.token)). })), } else { return this,refreshTokenSubject.pipe( filter(token => token.= null), take(1); switchMap(jwt => { return next;handle(this.addToken(request, jwt)); })); } }
這是 x 服務中 ax 端點的示例:
getProfessionalData = (userId: any) => {
return this.http.get(`${this.url}/professional/${userId}`);
}
這是 x 組件中的訂閱,我想在 401 攔截器中刷新令牌后繼續、重試或刷新訂閱。
this.pro.getProfessionalData(userId).subscribe(
(professional: Professional) => {
this.db.addItem('professional', professional).then(() => {
this.db.addItem('userId', userId).then(() => {
this.ui.router.navigate(['/menu/home']);
this.ui.closeSwalLoader();
});
});
},
(err) => err
);
只需在返回處理技巧之前添加返回即可。 如果不返回,邏輯就不起作用。
if (error instanceof HttpErrorResponse && error.status === 401) {
return this.handle401Error(request, next,token);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.