NgRx 到达 flatMap 函数内操作的有效载荷



我对 NgRx 比较陌生,我只使用它几个月了,这个问题我已经挣扎了好几天,从来没有在文档中找到任何有用的东西。

我也在将Angular 8与NgRx 8一起使用。这是我非常简单的虚拟代码。

获取项操作

export interface GetItems {
param: number;
}
export const getItems = createAction("[App] Get items", props<GetItems>());

获取项效果:

getItems$ = createEffect(
() =>
this.actions$.pipe(
ofType(AppActions.getItems),
tap((action) => console.log(action.param),
exhaustMap(action => this.appService.getItems()),
map((response: Item[]) => {
console.log(action.param);
return this.store.dispatch(
AppActions.getItemsComplete({ items: response })
);
})
),
{ dispatch: false }
);

调度 getItems 操作:

ngOnInit(): void {
const param: number = 99;
this.store.dispatch(getItems({ param }));
}

有没有办法在 exhaustMap 运算符到达操作的参数有效负载?正如你在这里看到的,第二个控制台.log将推送有关 missin 操作对象的错误。我的目标是:首先向appService发送请求(但没有 getItems 操作参数(,然后使用getItems操作参数调度getItemsComplete操作。

一种方法是这样的:

getItems$ = createEffect(
() =>
this.actions$.pipe(
ofType(AppActions.getItems),
tap((action) => console.log(action.param),
exhaustMap(action => forkJoin(of(action), this.appService.getItems())),
map(([action, response]) => {
console.log(action.param);
return this.store.dispatch(
AppActions.getItemsComplete({ items: response })
);
})
),
{ dispatch: false }
);

forkJoin 将确保两个可观察量都完成,然后它将进一步委托响应数组。您可以将N可观察量传递给forkJoin,但一旦全部完成,您将获得数组响应。

最新更新