我有一个Web应用程序,我使用Rx.js来处理事件流。该应用使用后端提供的rest api
。
我主要订阅api
电话,当请求完成后,我会渲染结果并重置其他控制状态(隐藏进度元素等)。
当身份验证令牌过期时,某些api
次呼叫可能会失败,我必须让用户再次登录(显示登录弹出窗口等)。
我很好奇有没有办法恢复"成功登录后的api呼叫流?用户无需提供其他操作来获取服务器响应的内容。
当前工作流程的原始示例:
var apiCallStream = $.ajaxAsObservable(params):
apiCallStream.subscribe(
result => renderResult(result),
err => handleError(err));
function handleError(err) {
if (err.xhr.error === 401) {
LoginPopup();
} else {
ErrorPopup(err);
}
}
答案 0 :(得分:2)
Here some some (very rough pseudo-code), but you could do this with retryWhen
:
// use Rx.DOM.get for an Observable Ajax GET
var source = Rx.DOM.get('/some/end/point')
.retryWhen(function(errors) {
// retryWhen: errors is a stream of errors
// whatever observable you return, when it emits, the
// observable you're operating on will be retried. (the entire thing)
return errors.filter(function(e) { return e.status === 401; })
// if status is 401, then tell the user to login
.flatMapLatest(function() { return doUserLogin; });
});
// a contrived observable that shows a form and
// return a stream of successful logins
var doUserLogin = Observable.create(function(observer) {
// show a form
var form = $('.my-form').show();
// when submit is fired on said form...
return Rx.Observable.fromEvent(form, 'submit')
// send a login over ajax
.flatMap(e => Rx.DOM.post('some/url/login', form.serialize()))
});
Hopefully that gives you something to start with.