NGXS异步操作

时间:2018-05-20 10:27:07

标签: action dispatch ngxs

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

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

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中,我得到: enter image description here 登录操作在LoginSucces操作之后,如果我在stases之间切换(@INIT,[Auth]登录成功和[Auth]登录),则疼痛总是相同的。 (待定值不应该移动?)

如果我在调用new dispatch之前添加了setTimeout函数:

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

我在devtools中得到了正确的行为排序,在这种情况下,它会移动的挂起值:

enter image description here

enter image description here

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

你能帮忙吗? 感谢

1 个答案:

答案 0 :(得分:1)

目前,这是由于NGXS的工作方式,即父动作仅在子动作完成后完成。 操作在完成后发布到开发工具,以便它们可以包括完成状态,这就是为什么您看到它们按此顺序通过。

这是github上存在的一个问题(很快就会重新开放)。在此问题中查看此评论: https://github.com/ngxs/store/issues/139#issuecomment-390673126

相关问题