如何在Ngrx效果中组合多个可观察物?

时间:2019-03-14 13:15:37

标签: angular rxjs observable ngrx

我的NGRX效果会发出API请求,然后调度一个新动作。在此新操作中,我需要访问初始操作,,但是在switchMap之后该引用会丢失

@Effect()
  public myAction$: Observable<Action> = this.actions$.pipe(
    ofType<DoSomethingRequest>(MyActions.DO_SOMETHING),
    switchMap((action)=> this.backendService.doSomething(action.id, action.payload),
    map(dto => new DoSomethingSuccess(/* here I need both action.payload and dto */))
  );

如何在链中保留原始动作?我需要动作和API调用的结果。

2 个答案:

答案 0 :(得分:0)

您可以重新构建链,使原始动作与第二个动作处于同一范围:

@Effect()
public myAction$: Observable<Action> = this.actions$.pipe(
  ofType<DoSomethingRequest>(MyActions.DO_SOMETHING),
  switchMap((action)=> this.backendService.doSomething(action.id, action.payload).pipe(
    map(dto => new DoSomethingSuccess(/* here I need both action.payload and dto */)),
  ),
);

在用例中,将map放在switchMap的内部还是外部都没关系。

答案 1 :(得分:-1)

您可以先引入副作用来存储您的动作。

@Effect()
  public myAction$: Observable<Action> = this.actions$.pipe(
    ofType<DoSomethingRequest>(MyActions.DO_SOMETHING),
    switchMap((action)=> {
      localStorage.setItem('pastAction', action);
      return this.backendService.doSomething(action.id, action.payload);
    }),
    map(dto => new DoSomethingSuccess(dto, localStorage.getItem('pastAction'))
  );