Ngrx:调度需要一个对象



在我的操作中,我有:

export const GetSwivlr = createAction(
GET_SWIVLR,
props<{ payload: Swivlr[] }>()
);......

我的减速器里有:

export const reducer = createReducer(
initialState,
on(SwivlrActions.AddSwivlr, (state, { payload }) => {
return adapter.addOne(payload, state)
}),
on(SwivlrActions.RemoveSwivlr, (state, { payload }) => {
return adapter.removeOne(payload, state)
}),
on(SwivlrActions.GetSwivlr, (state, { payload }) => {
return adapter.setAll(payload, state)
})
);

在我的效果中:

export class SwivlrEffects {
constructor(private crudService: CrudService,
private readonly actions$: Actions
) { }
public readonly getSwivlr$ = createEffect(() => 
this.actions$.pipe(ofType(GetSwivlr),
mergeMap(() => this.crudService.getAll<Swivlr[]>('endpointAddress').pipe(
map(swivlr => ({ type: GET_SWIVLR, payload: swivlr})))),
catchError((error: string | null) =>
of(FailSwivlr))
)
);
}

最初,我的所有操作都被声明为函数,而不是const,我将每个操作作为Action返回,而不是createAction。

使用我的Actions声明为函数的调度器时,没有造成任何错误:

this.store.dispatch({ type: GET_SWIVLR });

但现在确实如此,我想我只需要把电话改成:

this.store.dispatch(GetSwivlr());

然而,这个const附带了一个道具。这是我相信,在成功呼叫我的Api后,我的效果会得到填充。

有人能建议我如何更改这个电话吗?

我收到2个错误第一个:

错误:效果"SwivlrEffects.getSwivlr$";作为无效操作发送:未定义

第二个错误:

TypeError:Dispatch需要一个对象,但它收到了一个作用

要在我的组件中详细说明@Antons的答案,我现在有:

....
tiles$: Observable<Swivlr[]> = this.store.select(state => state.tiles);
returnval: Swivlr[];
constructor(private store: Store<{tiles: Swivlr[] }>) {
this.returnval = [];
}
ngOnInit() {
this.store.dispatch(GetSwivlr({ payload: this.returnval }));
}
....

正如您在这里声明的:

export const GetSwivlr = createAction(
GET_SWIVLR,
props<{ payload: Swivlr[] }>()
);

你必须为你的行动提供有效载荷,并像这样发送:

this.store.dispatch(GetSwivlr({ payload: `here is your object with type Swivlr[]` }));

实际上,您在完成操作时没有发送正确的操作。当您将操作更改为createAction版本时,可能没有更新它。下面代码中的括号可能会弄乱——请注意。

它也可能是SetSwivlr({ payload: swivlr })

getSwivlr$ = createEffect(() => 
this.actions$.pipe(
ofType(GetSwivlr),
mergeMap(() => this.crudService.getAll<Swivlr[]>('endpointAddress').pipe(
map(swivlr => GetSwivlr({ payload: swivlr })))), // <-- here
catchError((error: string | null) => of(FailSwivlr))
)
);
}

另一句话是,从商店中选择时,应该使用ngrx.io/guide/store/selectors,而不是在组件中使用this.store.select(state => state.tiles)