我正在尝试将我的功能 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、[Auth] 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 中对我的操作进行了正确排序,在这种情况下,它移动了挂起的值:
但是……我哪里错了?我不认为这是使用异步调度的正确模式!!
你能帮忙吗?谢谢