我在玩ngrx效果和rxjs时遇到问题。我正在使用两个版本的效果(为了解决这个问题而进行了简化):
版本1:
public effect$ = createEffect(() =>
this.actions$.pipe(
ofType(
actions.successAction1,
actions.successAction2,
...
),
scan((actionCount, typedAction) => actionCount + 1, 0),
filter((actionCount) => actionCount === 2), // If more actions, then this value is different
map((actionCount) => actions.finalAction())
)
);
版本2:
public effect$ = createEffect(() =>
this.actions$.pipe(
ofType(
actions.successAction1,
actions.successAction2
...
),
bufferCount(2), // If more actions, then this value is different
switchMap(() => actions.finalAction())
)
);
我真的不明白为什么第一个版本可以工作,而第二个版本却不能。我希望在调度 2 个操作(successAction1 和 successAction2)后调度“finalAction”。
bufferCount(2)
运算符将两个操作收集到一个数组中,但您需要在分派之前将该数组映射到finalAction
。
public effect$ = createEffect(() =>
this.actions$.pipe(
ofType(
actions.successAction1,
actions.successAction2
// ... add other action types
),
bufferCount(2),
filter((bufferedActions) => bufferedActions.length === 2),
switchMap((bufferedActions) => [
actions.finalAction(),
// You can also include the buffered actions if needed
// actions.someOtherAction(bufferedActions[0], bufferedActions[1]),
])
)
);