首页 > 解决方案 > NGXS 异步操作

问题描述

我正在尝试将我的功能 AuthModule Angular6 从 NgRX 重构为 NGXS。

我是一个国家的问题。里面有一个Action async:

export const initialState: State = {
  error: null,
  pending: false,
};


@State<State>({
  name: 'login',
  defaults: initialState
})
export class LoginPageState {

  @Selector()
  static error(state: State) {
    return state.error;
  }

  @Selector()
  static pending(state: State) {
    return state.pending;
  }

  constructor(private authService: AuthService) {
  }

  @Action(Login)
  login({getState, patchState, setState, dispatch}: StateContext<State>, {payload}: Login) {

    console.log('login da login page', getState());
    setState({...getState(), pending: true});
    console.log('login da login page', getState());

    return this.authService.login(payload)
      .pipe(
        map((user) => {
          // setTimeout(() => {
          return dispatch([new LoginSuccess({user})]);
          // }, 10);
        }),
        catchError(err => dispatch(new LoginFailure(err))));
  }

  @Action(LoginSuccess)
  loginSuccess({setState, getState}: StateContext<State>) {
    console.log('login success');
    setState({...getState(), error: null, pending: false});
  }

  @Action(LoginFailure)
  loginFailure({setState, getState}: StateContext<State>, {payload}: LoginFailure) {
    setState({...getState(), error: payload, pending: false});
  }

​
}

当我调度登录操作时它可以工作,但是在我的 redux devtools 中我得到: 在此处输入图像描述 登录操作在 LoginSucces 操作之后,如果我在状态(@INIT、[A​​uth] Login Success 和 [Auth] Login)之间切换,那么痛是总是一样。(挂起的值不应该移动?)

如果我在调用新调度之前添加一个 setTimeout 函数:

 return this.authService.login(payload)
  .pipe(
     map((user) => {
       setTimeout(() => {
         return dispatch([new LoginSuccess({user})]);
       }, 10);
     }),
     catchError(err => dispatch(new LoginFailure(err))));

我在 devtools 中对我的操作进行了正确排序,在这种情况下,它移动了挂起的值:

在此处输入图像描述

在此处输入图像描述

但是……我哪里错了?我不认为这是使用异步调度的正确模式!!

你能帮忙吗?谢谢

标签: actiondispatchngxs

解决方案


目前这是由于 NGXS 的工作方式导致父操作仅在其子操作完成后完成。操作在完成时发布到开发工具,以便它们可以包含完成时的状态,这就是您看到它们按此顺序执行的原因。

这是 github 上的一个现有问题(即将重新打开)。请参阅问题中的此评论: https ://github.com/ngxs/store/issues/139#issuecomment-390673126


推荐阅读