Rx.js 和应用程序工作流 [英] Rx.js and application workflow
问题描述
我有一个 Web 应用程序,我在其中使用 Rx.js 来处理事件流.该应用程序使用后端提供的 rest api
.
I've got a web application where I'm using the Rx.js for handling event streams. The app uses a rest api
provided by a backend.
大多数情况下,我订阅了 api
调用,当请求完成时,我会呈现结果并重置其他控件状态(隐藏进度元素等).
Mostly I make a subscription for an api
call and when a request is done I render results and reset other controls states (hide progress elements and so on).
某些 api
调用可能会在身份验证令牌过期时失败,我必须让用户再次登录(显示登录弹出窗口左右).
Some api
calls can be failed when an auth token is expired and I have to make a user to login again (show a login popup or so).
我很好奇有没有办法在成功登录后恢复"一个 api 调用流?用户无需提供额外操作即可获得服务器响应.
I'm curious is there a way to "restore" an api call stream after a successful login? Where a user has not to provide additional actions to get a server response.
当前工作流程的原始示例:
Primitive example of the current workflow:
var apiCallStream = $.ajaxAsObservable(params):
apiCallStream.subscribe(
result => renderResult(result),
err => handleError(err));
function handleError(err) {
if (err.xhr.error === 401) {
LoginPopup();
} else {
ErrorPopup(err);
}
}
推荐答案
这里有一些(非常粗略的伪代码),但你可以用 retryWhen
来做到这一点:
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.
这篇关于Rx.js 和应用程序工作流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!