本文介绍了Angular 2 RxJS可观察:重试,但状态为429的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了我的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?

Plunker上的实时演示

Angular 2 rc.6RxJS 5 Beta 11Typescript 2.0.2

推荐答案

您可以将429个错误的处理组合到传递给retryWhenerrors可观察对象中.如果是从服务器收到的错误,则从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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:10