NGRX效果不过滤动作/管道内部的功能被执行

时间:2018-08-19 22:22:09

标签: angular rxjs ngrx

我有效果,但是它里面的第一个switchMap之后的mergeMap被触发而没有触发GetPackageCalendar类型的动作

@Effect()
  loadCalendar$ = this.actions$
    .pipe(
      ofType(fromActions.GetPackageCalendar),
      switchMap(() => this.store.select(selectRouterState)),
      mergeMap(
        (state: RouterStateUrl) => this.store.select(selectCalendarParams).pipe(
          switchMap((calParams) => this.getPackageCalendar(state, calParams)),
          //this gets executed
        ),
      ),
      map((calendar: CalendarRS) => new fromActions.SetPackageCalendar(calendar)),
    );

`

发生了什么事?

我想从存储中选择两个值,并将它们作为参数传递给getPackageCalendar

2 个答案:

答案 0 :(得分:0)

  

我想从商店中选择两个值,并将它们作为参数传递给getPackageCalendar

为此使用withLatestFrom

@Effect()
loadCalendar$ = this.actions$.pipe(
  ofType(fromActions.GetPackageCalendar),
  withLatestFrom(
    this.store.select(selectRouterState),
    this.store.select(selectCalendarParams)
  ),
  mergeMap(([state, calParams]) => this.getPackageCalendar(state, calParams)),
  map((calendar: CalendarRS) => new fromActions.SetPackageCalendar(calendar))
);

答案 1 :(得分:0)

我的猜测是因为您的第一个store select中的switchMap部分。首次通话后,它会继续订阅GetPackageCalendar。在这种情况下,您只想选择一次存储值。因此请在执行后加入take(1)以自动退订。

@Effect()
loadCalendar$ = this.actions$
  .pipe(
    ofType(fromActions.GetPackageCalendar),
    switchMap(() => {
      // take one only
      const obs$ = this.store.select(selectRouterState).pipe(take(1));
      return obs$;
    }),
    ...
  );