问题描述
我已经编写了我的Observable(来自HTTP请求)以重试失败.但是,如果服务器响应429 Too many requests
错误,我想不重试.
I've composed my Observable (from an HTTP request) to retry on failure. However, I would like to not retry if the server responded with 429 Too many requests
error.
当前实现重试两次,相隔1秒,无论如何.
The current implementation retries twice, 1 second apart, no matter what.
return this.http.get(url,options)
.retryWhen(errors => {
return errors.delay(1000).take(2);
})
.catch((res)=>this.handleError(res));
errors
是可观察的.如何获取引起错误的基础Response
对象?有了它,我可以访问服务器的状态码,并且只有在不是429的情况下才重试:
errors
is an Observable. How can I get the underlying Response
object that caused the error? With it I can access the server's status code and only retry if it's not 429:
return this.http.get(url,options)
.retryWhen(errors => {
if($code == 429) throw errors;
else return errors.delay(1000).take(2);
})
.catch((res)=>this.handleError(res));
如何在retryWhen
中获取状态代码?
How can I get status code within retryWhen
?
Angular 2 rc.6
,RxJS 5 Beta 11
,Typescript 2.0.2
推荐答案
您可以将429个错误的处理组合到传递给retryWhen
的errors
可观察对象中.如果是从服务器收到的错误,则从errors
观察对象发出的错误将包含status
属性.
You can compose the handling of 429 errors into the errors
observable that's passed to retryWhen
. The errors that are emitted from the errors
observable will contain a status
property if they are errors that were received from the server.
如果您不想在发生429个错误时重试,而希望抛出一个错误,则可以执行以下操作:
If you don't want to retry when 429 errors occur and instead wish to throw an error you could do something like this:
return this.http.get(url,options)
.retryWhen((errors) => {
return errors
.mergeMap((error) => (error.status === 429) ? Observable.throw(error) : Observable.of(error))
.delay(1000)
.take(2);
})
.catch((res) => this.handleError(res));
相反,如果您希望可观察的HTTP完成而不发出错误或响应,则可以仅过滤429个错误.
If, instead, you wanted the HTTP observable to complete without emitting either an error or a response, you could simply filter 429 errors.
这篇关于Angular 2 RxJS可观察:重试,但状态为429的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!