3 回答
TA贡献1847条经验 获得超7个赞
事件的顺序如下:
你发送一个AddUser动作
this.store.dispatch(new AddUser('USER'));
Reducer 被调用,状态被改变并被userAdded设置为false
case ADD_USER: {
return {
...state,
userAdded: false
}
},
调用选择器并通知订阅者,但您还没有任何订阅
调用EffectADD_USER并将异步请求发送到userService
login$ = createEffect(() =>
this.actions$.pipe(
ofType(UserAction.ADD_USER),
exhaustMap(action =>
this.userService.addUser("USER").pipe(
map(user => UserAction.AddUserSuccess({ "user" })),
catchError(error => of(UserAction.AddUserFail({ error })))
)
)
)
);
您在管道中订阅带有getUser运算符的选择器take(1)
this.store.pipe(select(getUser), take(1)).subscribe((isUserAdded) => {
if(isUserAdded) {
this.router.navigateByUrl('/success');
} else {
this.router.navigateByUrl('/home');
}
});
userAdded选择器从商店返回标志的值false,您的回调函数被调用,订阅被take(1)运营商取消
路由器导航到“/home”
来自的响应userService已返回且userAdded标志设置为true但您的订阅已被取消
如果您想要一个简单的解决方案component.ts,只需尝试订阅take(2), skip(1):
this.store.pipe(select(getUser), take(2), skip(1)).subscribe((isUserAdded) => {
if(isUserAdded) {
this.router.navigateByUrl('/success');
} else {
this.router.navigateByUrl('/home');
}
});
TA贡献1852条经验 获得超7个赞
你不能只在你的效果 fn 中返回两个动作,比如 UserAddedSuccess 并在 catchError UserAddedFail 中写另一个效果,它将监听 useraddedsuccess 动作并在成功时重定向所需的页面,在第一个效果 catcherror 返回 UserAddedFail 动作和相同的过程?
TA贡献1828条经验 获得超3个赞
我想你可以分派多个动作,你必须创建单独的动作来处理路由。
login$ = createEffect(() =>
this.actions$.pipe(
ofType(UserAction.ADD_USER),
exhaustMap(action =>
this.userService.addUser("USER").pipe(
switchMap(user => [
UserAction.AddUserSuccess({ "user" }),
routeAction.routeto('success')
])
,catchError(error => [
UserAction.AddUserFail({ error }),
routeAction.routeto('Home');
])
)
)
)
);
添加回答
举报