[英]Angular 5 - Response HttpInterceptor - retry on timeout (504)
我嘗試實現一個 HttpInterceptor 來重試超時的請求。 我實現了以下代碼,但 err 不包含狀態代碼,因此它不起作用。
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.retryWhen(error => {
return error
.flatMap((err) => {
if (err instanceof HttpErrorResponse && err.status === 504) { // timeout
return Observable.of(err.status).delay(5000);
}
return Observable.throw({ error: 'No retry' });
})
.take(1)
.concat(Observable.throw({ error: 'Sorry, there was an error (after 5 retries)' }));
});
}
}
err 對象具有以下對象(注意狀態為 0):
誰能幫我?
提前致謝!
---- 更新 ---- 經過更深入的分析,我發現問題在於我有另一個攔截器將 Auth 標頭添加到我的請求中。 我創建了一個 stackblitz 示例來顯示這個問題: https ://stackblitz.com/edit/angular-interceptors-azhwak 在上面的示例中,您可以檢查錯誤代碼是否始終為 0(零),即使錯誤是 504。如果您注釋掉另一個攔截器 (I2),代碼將按預期工作。
不確定我是否做錯了什么,或者我不應該有多個攔截器(一些更新請求,一些更新響應)?
更新 2
用戶@AngularInDepth.com 是對的,問題是沒有提供 CORS。 設法使用不同的服務使其工作。 但是現在我面臨一個不同的問題,我只想在第一次重試后調用第二個攔截器(I2)。 有沒有辦法做到這一點?
查看更新的示例: https : //stackblitz.com/edit/angular-interceptors-ckbvsb
謝謝
問題在於服務https://httpstat.us/504
本身。 當您向請求添加自定義標頭時,它不會正確處理 CORS,因此 XHR 請求錯誤而不是發出請求。 當 XHR 出錯時,您將獲得0
狀態,因為沒有發出請求。 這是演示這一點的plunker和代碼:
request() {
const url = 'https://httpstat.us/504';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
// when commented out `onload` handler is executed, otherwise `onerror`
// xhr.setRequestHeader('any', 'any');
xhr.onload = () => {console.log('loaded')};
xhr.onerror = () => {console.log('errror')};
xhr.send();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.