使用动作创建者时,从ngrx中的效果调度不同的动作类型



我想写一个效果,根据某些条件从存储和调度操作中获取一些数据。我有我的效果像这个

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获取了它,并将action和一些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 } }>()
);

我找到了解决问题的方法。我试着写了两个效果,它要么返回[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;
})
)
);

注意:问题是我必须为每个新条件写一个新的效果。

最新更新