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');
])
)
)
)
);
添加回答
舉報