我正在使用API返回HTTP“202 Accepted”响应并开始处理长时间运行的请求。
然后我需要在延迟之后发布相同的请求,直到我收到HTTP“200 OK”响应,此时我可以从响应正文中查询结果。
我查看了文档并找到了几个重试错误的例子,但是在成功延迟后我找不到如何重试。
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
@Injectable()
export class WebService {
private _serviceUrl = 'https://webservice.com/api/long_request';
constructor(private _http: HttpClient) { }
getData() {
let body = JSON.stringify({
"time_properties":
{
"start_date": "2017-08-10",
"end_date": "2017-08-14"
}
});
return this._http.post(this._serviceUrl, body)
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse) {
console.error(err.message);
return Observable.throw(err.message);
}
}
答案 0 :(得分:1)
如上所述,请在此时使用重试。当你有500个错误时,这将重试3次
.retryWhen((errors) => {
return errors.scan((errorCount, err) => {
if (this.isNoUserError(err, this.unwrapHttpError(err))) {
if(errorCount >= 3) {
// return Observable.throw();
throw err;
}
return errorCount++;
} else {
throw err;
}
}, 0);
})
private isNoUserError(error, unwrapError) {
return error.status === 500 && !!unwrapError && unwrapError.errorKey === "NO_USER";
}
private unwrapHttpError(error: any): any {
try {
return (error.json());
} catch (jsonError) {
return ({
code: -1,
message: "An unexpected error occurred."
});
}
}
成功再开始
loadSomething() {
this.http.load().then(() => {
if (code=== 202) {
this.loadSomehitng();
}
})
}