首页 > 解决方案 > NGXS - 如何在多个流上使用一个动作处理程序

问题描述

我有几个异步运行的动作,比如说VerifyEmailchangepassword. 我想在动作开始时显示一个加载器,并在拍卖结束时隐藏它。我知道我可以通过这种方式为每个动作做到这一点:

this.actions$
    .pipe( ofActionDispatched(VerifyEmail) )
    .subscribe( () => {
        this.showLoader();
    });
this.actions$
    .pipe( ofActionSuccessful(VerifyEmail) )
    .subscribe( () => {
        this.hideLoader();
    });

但是每个异步操作都有两个块,我想知道是否有办法将多个操作组合到一个管道中?像ofActionDispatched([VerifyEmail, ChangePassword])什么?

标签: ngxs

解决方案


您可以将运算符组合为多个操作,如下所示:

ofActionDispatched(VerifyEmail, ChangePassword)

请注意,它只是向方法添加参数而不是数组。

作为替代方案,您可以将此加载程序绑定到loading您所在州某处的道具,@Action并在执​​行异步工作之前和之后从您各自的处理程序更新它:

@Action(VerifyEmail)
async verifyEmail(ctx, action){
    ctx.patchState({ loading: true });
    await someasyncWork();
    ctx.patchState({ loading: false });
}

另一种选择是在调度完成之前和之后从 UI 组件调用它:

this.showloader();
this.store.dispatch(new VerifyEmail())
    .subscribe(() => this.hideLoader());

希望这可以帮助。


推荐阅读