是否可以推迟处理有效的操作,直到调度其他操作为止? 这里是确切的场景:
1.调度 Action A1
2.作用处理A1并请求http调用
3.在http调用完成之前调度B1 Action
4.effect想要处理Action B1,但它需要一部分store,直到“A1 http request”完成后才准备好
我通过变量内部效果类来处理它,但我正在寻找更干净的解决方案。这是我的代码
numberOfDelaying=0;
handleB1 = createEffect(() => {
return this.actions.pipe(
ofType(DashboardActions.B1),
withLatestFrom(this.store.pipe(select(someSelector))),
concatMap(([action, stateSlice]) => {
//need the state slice which is not ready until A1 is completed
if(!stateSlice && this.numberOfDelaying<10){ // here i check if the data is not ready dispatch B1 after 100 ms
this.numberOfDelaying++;
return of(DashboardActions.B1()).pipe(delay(100));
}
else if (stateSlice){
// do some async call
}
else {
return of(DashboardActions.Error())
}
})
);
});
最佳答案
这可能是一种方法:
handleB1 = createEffect(
() => this.actions.pipe(
ofType(DashboardActions.B1, DashboardActions.A1),
pairwise(),
switchMap(
// Wait for `A1` to send the new state only if the prev action was `A1`
([prevAction, crtAction]) =>
prevAction.type === DashboardActions.A1.type
? this.store.pipe(
select(someSelector),
skip(1) // Wait until the `A1` sends its new state
first(),
mapTo(crtAction)
)
: of(crtAction)
)
/* ... */
)
)
您可以为 ofType
指定多个操作:ofType(DashboardActions.B1, DashboardActions.A1, ...),
。
正如您所提到的,在 handleA1
中,您将在进行 http 调用之前调度 B1
操作。 A1
操作也会被 handleB1
拦截,因此当从 handleA1
分派(dispatch) B1
时>,在 handleB1
中,[prevAction, crtAction]
对将是这样的:[A1, B1]
。
然后,您将选择 A 切片
,但您需要跳过现有状态,因为它将是旧状态,并且仅在新状态到达时才继续,即当异步操作handleA1
将会完成。
关于javascript - ngrx 推迟生效的操作,直到调度另一个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61743050/