我必須進行輪詢,直到收到已完成的回應。但我也想只進行 2 分鐘的輪詢并防止無限輪詢為此我使用超時運算子,但這似乎不起作用。
interval(5000)
.pipe(
startWith(0),
switchMap(() => this.someService.getQueueJob(jobId)),
takeUntil(this.stopPolling),
timeout(2*60000)
)
.subscribe((res) => {
this.jobStatus = res.attributes.status;
if (this.jobStatus === 'Completed') {
this.fileUploadStatus = 'success';
this.stopPolling.next();
} else if (this.jobStatus === 'Failed') {
this.fileUploadStatus = 'error';
this.stopPolling.next();
}
});
此外,我需要在超時發生時拋出錯誤并通知用戶。
uj5u.com熱心網友回復:
在timeout將復位每次有一個排放。所以對于每次發射的interval和相應的this.someService.getQueueJob()它的復位。你可以使用一個額外的完成你的需求takeUntil與timer功能。
還
- 您在問題中說 2 分鐘超時,但代碼只有一分鐘。?
- 正如@Chris 在評論中提到的,您可以將
interval(5000)startWith(0)組合替換為timer(0, 5000).
timer(0, 5000).pipe(
switchMap(() => this.someService.getQueueJob(jobId)),
takeUntil(this.stopPolling),
takeUntil(timer(120000))
).subscribe(
...
);
編輯 1:將interval(5000) 替換startWith(0)為timer(0, 5000)
uj5u.com熱心網友回復:
您可以timer在啟動時使用超時:
// set time for timeout
timer(2 * 60000).pipe(
// trow error when timer emit event after 2 minutes
map(() => { throw new TimeoutError() }),
// put startWith operator to start before timer emit timeout event
startWith(0),
// switch to polling timer for every 5 second
switchMap(() => timer(0, 5000)),
// get date from http
switchMap(() => this.someService.getQueueJob(jobId)),
// stop manually the polling
takeUntil(this.stopPolling),
).subscribe(
(data) => console.log(data),
(error) => {
if (error instanceof TimeoutError)
console.log('time out')
else
console.log('http error')
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370258.html
上一篇:無法以角度從決議器獲取資料
