【问题标题】:Intercepting all action sent to the NgRx Store拦截发送到 NgRx 存储的所有操作
【发布时间】:2021-12-07 18:55:17
【问题描述】:

我是 NgRx 的新手。 我做了一些代码,但结果并不完全符合预期。 我想拦截使用dispatch() 函数发送到商店的每个动作。

我的目标如下:

  1. 在自定义效果中拦截发送到商店的每个动作,并将文本(拦截动作...)打印到控制台而不修改动作。 (处理此操作的 Effect 应该可以正常工作。)
  2. 如果操作(之前发送到商店)完成了它的工作(即相应的 Reducer 对商店进行了修改),我还想对此做出“反应”,并打印另一条消息(从商店获得状态。 ) 在控制台上

我的代码有 2 个问题:

  1. 文本以错误的顺序出现(即首先是“Got state from store”,然后是“Intercepting action...”,然后是“Got state from store”)。
  2. 为了拦截每个动作,我创建了一个包含所有动作的数组,在应用程序中定义,并用这个数组调用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) {}
}

感谢您的任何建议。

【问题讨论】:

    标签: action ngrx store


    【解决方案1】:

    请问您为什么需要这个? 回答问题:

    1. AFAIK 你不能这样做。一个动作首先到达所有减速器,然后由效果处理。如果您想在动作到达减速器之前注册它们,请查看元减速器。

    2. 要对效果中的所有动作做出反应,不要使用 ofType 运算符,而只需订阅动作流。

    【讨论】:

    • 感谢您的提示。我尝试控制自定义加载栏;即(动作开始)->(显示栏)分别。 (动作结束)->(隐藏栏)。并非所有操作都执行 http-req。我应该检查商店的状态来完成这个吗?您是否允许我提出 2 个其他问题?: 1)“......动作首先到达减速器......”:这是否意味着对应的 on()。触发减速器并计算每个匹配的“select(...)”语句? 2) 在语句“createEffect(() => this._actions.pipe(ofType(SomeAction), share()), { dispatch: false });”中: 指定“share()”和“dispatch”的目的是什么?
    • 1) 是 2) 你不需要分享,发送所以操作不会发送到商店
    • 感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2019-12-06
    • 2015-02-27
    • 1970-01-01
    • 2018-05-26
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多