使用NGX和状态管理的开放模式 [英] Opening modal using NGX and state management

查看:99
本文介绍了使用NGX和状态管理的开放模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用NGXS打开模式,该模式将设置数据表的列可见性.

I'd like to use NGXS to open modal which will set column visibility for datatable.

这是我的代码:

state.ts文件:

state.ts file:

@Action(OpenColumnModal)
openColumnModal(ctx: StateContext<FeedStateModel>) {
    const state = ctx.getState();
    const allCols = state.allColumns;
    return this.modalService.openColumnVisibilityModal(allCols).pipe(tap((result) => {
        ctx.setState({
            ...state,
            allColumns: result,
            userColumns: result.filter(col => col.visible)
        });
    })
}

modal.service.ts:

modal.service.ts:

openColumnVisibilityModal(columns): Observable<any> {
    const dialogRef = this.dialog.open(ColumnVisibilityModal, {
        data: columns,
        autoFocus: false,
        hasBackdrop: true,
        disableClose: true
    });

    return dialogRef.afterClosed();
}

当我使用NGXS打开的模式时,关闭后不会发出state事件.之后,我需要单击某处以调用openColumnModal函数内的回调函数.

When I'm using modal opened by NGXS, after closing the state event isn't emitted. After that, I need to click somewhere to call the callback function inside openColumnModal function.

我正在使用Angular Material对话框.

I'm using Angular Material dialog.

有人知道关闭模式后如何自动调用回调函数吗?

Does anyone know how to call callback function automatically after closing modal?

提前感谢:)

推荐答案

P.S. -建议在动作处理程序中订阅的其他答案不正确,因为NGXS不能那样工作!

P.S. - other answers that advise to subscribe inside the action handler are not correct, as NGXS doesn't work like that!

您当前的方法是正确的,问题是动作处理程序在Angular的区域之外运行.只需将NgZone类注入您的状态并在Angular的区域内执行代码即可:

Your current approach is correct, the problem is that action handlers are run outside Angular's zone. Just inject the NgZone class into your state and execute the code within Angular's zone:

constructor(private modalService: ModalService, private zone: NgZone) {}

@Action(OpenColumnModal)
openColumnModal(ctx: StateContext<FeedStateModel>) {
  const state = ctx.getState();
  const allCols = state.allColumns;
  return this.zone.run(() =>
    this.modalService.openColumnVisibilityModal(allCols).pipe(
      tap(result => {
        ctx.setState({
          ...state,
          allColumns: result,
          userColumns: result.filter(col => col.visible)
        });
      })
    )
  );
}

当您调度任何操作时-NGXS使用runOutsideAngular在父区域内为此操作调用相应的处理程序,这是设计使然.

When you dispatch any action - NGXS invokes the appropriate handlers for this action within the parent zone using runOutsideAngular, this is by design.

您还可以查看 executionStrategy选项,该选项可以提供自己的类或使用现有的NoopNgxsExecutionStrategy,根本不使用NgZone类.

You can also look at the executionStrategy option that allows to provide own class or use existing NoopNgxsExecutionStrategy, that doesn't use NgZone class at all.

这篇关于使用NGX和状态管理的开放模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆