【问题标题】:NGXS Async ActionsNGXS 异步操作
【发布时间】:2018-10-30 05:24:33
【问题描述】:

我正在尝试将我的功能 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 中对我的操作进行了正确排序,在这种情况下,它移动的挂起值:

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

你能帮忙吗? 谢谢

【问题讨论】:

    标签: action dispatch ngxs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 2019-06-22
      • 2023-03-16
      • 1970-01-01
      • 2018-11-16
      • 2023-03-31
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多