NGRX效果:单独调度多个动作

时间:2019-02-27 12:01:44

标签: angular rxjs observable ngrx ngrx-effects

我有以下效果:

  @Effect()
  bookingSuccess$: Observable<Action> = this.actions$.pipe(
    ofType(BookingActionTypes.BOOK_SEAT_SUCCESS),
    map((action: BookSeatSuccess) => action.payload.userUuid),
    switchMap(userUuid => [
      new SetConfirmation({confirmationType: ConfirmationType.Booking}),
      new GetAllBookings({floorId: this.configService.getSelectedFloorId()}),
      new HighlightUser({highlightedUser: userUuid})
    ])
  );

我的目标是延迟执行最后一个动作。

不幸的是,将其放在自己的switchMap中是行不通的,至少不是这样,因为那样一来,一切都会被延迟:

@Effect()
  bookingSuccess$: Observable<Action> = this.actions$.pipe(
    ofType(BookingActionTypes.BOOK_SEAT_SUCCESS),
    map((action: BookSeatSuccess) => action.payload.userUuid),
    switchMap(userUuid => {
      // DOES NOT WORK, BECAUSE NOW ALL ACTIONS ARE DELAYED 5s
      return of(new HighlightUser({highlightedUser: userUuid})).pipe(delay(5000));
    }
    switchMap(() => [
      new SetConfirmation({confirmationType: ConfirmationType.Booking}),
      new GetAllBookings({floorId: this.configService.getSelectedFloorId()})
    ])
);

如何调度多个动作并延迟处理不同的动作/异步动作?

1 个答案:

答案 0 :(得分:2)

您可以代替数组返回merge(静态变体),然后将每个动作转换为Observable,并仅用delay()延迟最后一个动作。

switchMap(userUuid => merge(
  of(new SetConfirmation({confirmationType: ConfirmationType.Booking})),
  of(new GetAllBookings({floorId: this.configService.getSelectedFloorId()})),
  of(new HighlightUser({highlightedUser: userUuid})).pipe(
    delay(1000),
  ),
)),