我有一个登录流程设置。假设我有这种情况,用户使用错误的凭据单击登录按钮,我调度登录操作并期望API产生不良结果,我在UI中显示了错误处理程序错误,用户放置了新的凭据,正确的,我应该能够重复上述过程。
对我来说没有发生。调度员只开火一次。我是ngrx的新手,不确定自己在哪里做错了,但这是我的代码:
登录方法:
logInUser(user: User) {
this.store$.dispatch(new fromUserActions.LoginUser(user));
this.actions$.ofType(fromUserActions.LOGIN_USER_FAIL);
}
副作用:
@Effect()
loginUser$ = this.actions$
.pipe(
ofType(fromUserActions.LOGIN_USER),
map((action: fromUserActions.LoginUser) => action.payload),
switchMap(payload => this.userService.loginUser(payload)),
map((user) => fromUserActions.LoginUserSuccess(user)),
catchError((error) => of(new fromUserActions.LoginUserFail(error.message)))
);
失败操作:
export class LoginUserFail implements Action {
readonly type = LOGIN_USER_FAIL;
constructor(public payload: any) { }
}
这是redux开发工具的屏幕截图。如您所见,第一次执行动作登录和失败均正常,然后才触发登录动作。
答案 0 :(得分:0)
您必须在内部可观察的this.userService.loginUser(payload)
上捕获错误。
答案 1 :(得分:0)
问题是 this.actions $ .ofType(fromUserActions.LOGIN_USER_FAIL); 。只需将其删除。
logInUser(user: User) {
this.store$.dispatch(new fromUserActions.LoginUser(user));
this.actions$.ofType(fromUserActions.LOGIN_USER_FAIL); <--- Remove
}
并且您已经通过管道传递了api调用的响应。
@Effect()
loginUser$ = this.actions$
.pipe(
ofType(fromUserActions.LOGIN_USER),
map((action: fromUserActions.LoginUser) => action.payload),
switchMap(
payload => this.userService.loginUser(payload).pipe(
map((user) => new fromUserActions.LoginUserSuccess(user)),
catchError((error) => new fromUserActions.LoginUserFail(error.message))
)
),
);