我的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调用的结果。
答案 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'))
);