1

我对 NgRx 相对较新,我只使用了几个月,这个问题我一直在努力解决好几天,但从未在有关此的文档中找到任何有用的信息。

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

获取项目操作

export interface GetItems {
  param: number;
}

export const getItems = createAction("[App] Get items", props<GetItems>());

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 }));
}

有没有办法在排气映射操作符内到达动作的参数有效载荷?正如您在此处看到的,第二个console.log将推送有关 Missin 操作对象的错误。我的目标是:首先向appService发送请求(尽管没有getItems操作参数),然后使用getItems操作参数调度getItemsComplete操作。

4

1 回答 1

0

一种方法是:

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将确保两个 observables 都完成,然后它将响应数组委托到管道的下方。您可以将Nobservables 传递给,但一旦完成forkJoin,您将获得数组响应。

于 2020-01-09T07:54:46.167 回答