我正在尝试轮询对我的后端的API调用。这个想法是服务器将发送202错误,直到完成处理作业为止,并且在请求过多后将返回200,并显示一些结果。我不希望该错误终止该流。API调用仅进行一次。
“ rxjs”:“〜6.4.0”,“ @ angular / core”:“〜8.2.14”
启动代码:
onSubmit() {
return this.scraperService.postUrl(this.form.value.url)
.pipe(
switchMap( val => {
return this.scraperService.pollUntilTaskFinished(val);
})
).subscribe( val => console.log(val))
}
服务代码:
postUrl(url: string): Observable<any> {
return this.http.post('/api/start', {url})
.pipe(
map((res: { jobId: string }) => {
if (res.jobId) {
return res.jobId;
}
}));
}
pollUntilTaskFinished(jobId): Observable<any> {
return interval(2000)
.pipe(
switchMap(() => this.http.get(`/api/results/${jobId}`)))
.pipe(
catchError(err => this.handleError(err)),
map(res => console.log(res)));
}
handleError(data: HttpErrorResponse) {
if (data.status === 202) {
return of('continue');
}
}
如何确保间隔重复,直到得到200所需的JSON?
如果您不想处理链,则必须先捕获错误,然后再将其传播到主链。这意味着将其捕获到内部switchMap()
:
this.http.get(`/api/results/${jobId}`))
.pipe(
catchError(err => this.handleError(err)),
)
您完全正确,该错误是在服务器上发生的,未被捕获。谢谢