我想编写一个效果,该效果根据某些条件从存储和调度动作中获取一些数据。我的效果是这样的
onManageTab$ = createEffect(() =>
this.actions$.pipe(
ofType(TabsActions.manageTab),
// The idea to go with switchMaps and forkjoins over withLatestFrom is
// `withLatestFrom` fetches undefined state here (think store is not properly created at that point)
switchMap(action =>
forkJoin(
of(action),
this.store.select(TabSelectors.getAllTabsInfo).pipe(take(1))
)
),
switchMap( ([action, tabsInfo]) => {
if (someCond) {
return [ TabsActions.addTab({ payload: {pageInfo: action.payload.pageInfo} })];
}
return [TabsActions.updateActiveTab({ payload: {pageID: existingTabID} })];
// some workaround to make it work
return of({
type: '[Tab] Dummy action',
});
})
)
);
我面临使用withLatestFrom
从商店中获取最新值的问题,因此我设法使用switchMap
来获取它,并将动作和一些tabInfo传递给另一个switchMap
。现在,我想根据某些情况调度其他操作。 (注意:我使用额外的payload
道具创建了我的减速器和动作,我对此进行了相应的处理)
如果删除虚拟动作的返回('[Tab] Dummy action'
),则会出现以下错误
Type 'Observable<{}>' is not assignable to type 'Observable<Action>'.
Property 'type' is missing in type '{}' but required in type 'Action'.
Argument of type
'([action, tabsInfo]: [{ payload: { pageInfo: PageInfo; }; } & TypedAction<"[Tab] Manage tab">, PageInfo[]]) => Observable<{ type: string; payload: { pageInfo: PageInfo; }; }> | Observable<{ type: string; payload: { ...; }; }>'
is not assignable to parameter of type
'(value: [{ payload: { pageInfo: PageInfo; }; } & TypedAction<"[Tab] Manage tab">, PageInfo[]], index: number) => ObservableInput<{ type: string; payload: { pageInfo: PageInfo; }; }>'.
我了解这会引发错误,因为操作中的有效负载不同。但是,不可能根据条件分派具有不同有效负载的动作。
如果我有一个没有有效载荷作为返回值的动作,为什么会起作用?
[如果您想知道完整的错误跟踪以获取更多见解,请告诉我
编辑:以下是我创建动作的方式
export const addTab = createAction(
'[Tab] Add tab',
props<{ payload: { pageInfo: PageInfo } }>()
);
export const updateActiveTab = createAction(
'[Tab] Update active tab',
props<{ payload: { pageID: string } }>()
);
我找到了解决我问题的方法。我尝试编写2个效果,它们返回[Action]
或EMPTY
onManageTabCondTrue$ = createEffect(() =>
this.actions$.pipe(
ofType(TabsActions.manageTab),
switchMap(action =>
forkJoin(
of(action),
this.store.select(TabSelectors.getAllTabsInfo).pipe(take(1))
)
),
switchMap( ([action, tabsInfo]) => {
if (someCond) {
return [ TabsActions.addTab({ payload: {pageInfo: action.payload.pageInfo} })];
}
return EMPTY;
})
)
);
onManageTabCondFalse$ = createEffect(() =>
this.actions$.pipe(
ofType(TabsActions.manageTab),
switchMap(action =>
forkJoin(
of(action),
this.store.select(TabSelectors.getAllTabsInfo).pipe(take(1))
)
),
switchMap( ([action, tabsInfo]) => {
if (!someCond) {
return [TabsActions.updateActiveTab({ payload: {pageID: existingTabID} })];
}
return EMPTY;
})
)
);
注意:问题是我必须为每个新条件编写一个新效果。