Javascript 使用flatMapLatest处理错误并重试
我有一个网页,其中有一系列的项目,用户可以点击。根据项目的类型,单击任何项目都会向服务器发送ajax请求,然后显示更多项目。 如果请求导致错误,我希望显示它,然后允许用户像以前一样继续单击或与页面交互 我的代码如下所示Javascript 使用flatMapLatest处理错误并重试,javascript,rxjs,reactive-extensions-js,Javascript,Rxjs,Reactive Extensions Js,我有一个网页,其中有一系列的项目,用户可以点击。根据项目的类型,单击任何项目都会向服务器发送ajax请求,然后显示更多项目。 如果请求导致错误,我希望显示它,然后允许用户像以前一样继续单击或与页面交互 我的代码如下所示 $scope.$createObservableFunction("clickHandler") .flatMapLatest(function (args) { //send the ajax request to the server })
$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
})
.retry()
.subscribe(function (data) {
//handle getting the data from the server
})
我具体在哪里可以处理错误案例?我预计会发生错误,我总是希望重新订阅源代码,但我希望有机会处理该错误。诀窍是将错误转化为数据:
$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
var ajaxQuery = someObservable;
// turn the observable into
// a stream of eithers, which will
// either have a 'result'
// or an 'error'
// use .catch() to turn the error
// into a either with an error property
// use .map() to turn the success
// into a either with the result property
return ajaxQuery
.map(function (result) {
return { result: result };
})
.catch(function (error) {
return Rx.Observable.of({ error: error });
});
})
.subscribe(function (data) {
if (data.error) {
// display data.error to user
}
else {
// display data.result to user
}
})
如果ajax方法返回一个承诺
,请使用然后
链接:
$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
var ajaxQuery = somePromise;
// turn the promise into
// a promise of eithers, which will
// either have a 'result'
// or an 'error'
return ajaxQuery
.then(function onSuccess(result) {
return { result: result };
}, function onError (error) {
return { error: error };
});
})
.subscribe(function (data) {
if (data.error) {
// display data.error to user
}
else {
// display data.result to user
}
})
什么是
函数(args)={
?很抱歉,我使用了TypeScript,正在将(args)=>{}
转换为函数(args){}
但是忘记了=
:)传递给catch
的方法应该返回一个可观察的这正是我所需要的。非常感谢。我花了很多时间阅读了Rx中所有不同类型的错误处理,但我自己无法理解。再次感谢!