问题描述
我试图了解如何使用可观察的序列以及如何从错误中恢复.
I'm trying to understand how to consume observable sequences and how to recover from errors.
我的示例有些人为,但是我的实际实现太复杂了,无法在此处显示.无论如何,我有someObservable
,当用户单击UI时会发出值.这应该触发对API的请求(GET/POST/etc).问题在于,如果API返回错误,此后将不再调用postData
.
My example is a bit contrived but my real implementation is a bit too complex to show here. Anyway, I have someObservable
that emits values when the user clicks in the UI. This should trigger a request to the API (GET/POST/etc). The problem is that if the API returns an error, postData
isn't called anymore after that.
我在这里举一个例子来说明问题.我发现我可以使用Rx.Observable.of
而不是Rx.Observable.throw
来保持运行.但这将向subscribe
函数发出一个值.在我的实际应用程序中,postData
是一项服务,该服务可以被应用程序的多个部分重用,并且我不确定是否要在其中使用of
而不是throw
.
I've make an example here that shows the problem. I've found that I can use Rx.Observable.of
instead of Rx.Observable.throw
to keep things running. But that will emit a value to the subscribe
function. And in my real application postData
is a service that is reused by multiple parts of the application and I'm not sure that I want to use of
instead of throw
there.
所以我的问题是,您通常如何处理此类事情?
So my question is, how do you normally handle things like these?
let someObservable = Rx.Observable.timer(1, 1000);
someObservable
.switchMap(data => {
return postData(data);
})
.catch(error => {
console.log("POST failed");
})
.subscribe(val => console.log("Success: " + val));
function postData(data) {
console.log("Will post " + data);
if (data !== 2) {
return Rx.Observable.of(true);
}
else {
return Rx.Observable.throw(new Error("400 Bad Request or something"));
}
}
http://jsbin.com/naroyeyive/3/edit?js,console
推荐答案
如果要再次发送请求,则可能要查看retry
和retryWhen
而不是catch
.
If you want to send the request again, you may want to look into retry
and retryWhen
instead of catch
.
catch
将使用返回的Observable
作为新的源". 请参阅此bin以获取示例.
catch
will use the returned Observable
as new "source". See this bin for an example.
retry(When)
将根据您传递给操作员的配置,在发生错误时重新订阅".您可以在此处找到示例和更多信息: https://www.learnrxjs.io/operators /error_handling/retrywhen.html
retry(When)
will "re-subscribe" whenever an error occurs, based on the configuration you pass to the operators. You can find examples and more information here: https://www.learnrxjs.io/operators/error_handling/retrywhen.html
这篇关于如何从rxjs中的错误中恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!