【发布时间】:2021-12-07 18:55:17
【问题描述】:
我是 NgRx 的新手。
我做了一些代码,但结果并不完全符合预期。
我想拦截使用dispatch() 函数发送到商店的每个动作。
我的目标如下:
- 在自定义效果中拦截发送到商店的每个动作,并将文本(拦截动作...)打印到控制台而不修改动作。 (处理此操作的 Effect 应该可以正常工作。)
- 如果操作(之前发送到商店)完成了它的工作(即相应的 Reducer 对商店进行了修改),我还想对此做出“反应”,并打印另一条消息(从商店获得状态。 ) 在控制台上
我的代码有 2 个问题:
- 文本以错误的顺序出现(即首先是“Got state from store”,然后是“Intercepting action...”,然后是“Got state from store”)。
- 为了拦截每个动作,我创建了一个包含所有动作的数组,在应用程序中定义,并用这个数组调用
ofType()。如果实施了新操作,我必须手动更新此数组。有没有办法直接从商店中检索注册的操作?
下面是代码:
app.module.ts
//to register the Effect to intercept the actions
imports: [
EffectsModule.forRoot([InterceptorEffects]),
]
app.component.ts
//here I react to the changes of the store
_interceptorSubscription: Subscription;
this._interceptorSubscription = _store.pipe(select((state, props) => console.log("Got state from store.")) );
interceptor.effect.ts
//the Effect that should intercept every action
@Injectable({ providedIn: "root" })
export class InterceptorEffects {
private readonly _interceptAllAction$ = createEffect(() =>
this._actions.pipe(
ofType(...[JobActions.downloadResultAction, JobActions.deleteJobAction]),
tap(() => console.log("Intercepting action..."))
)
, { dispatch: false } );
constructor(private _actions: Actions) {}
}
感谢您的任何建议。
【问题讨论】: