awgold90
awgold90

Reputation: 72

Intercepting all action sent to the NgRx Store

I'm new with NgRx. I made some code, but the result is not exactly what intended. I would like to intercept every action sent with the dispatch() function to the store.

My goals are the following:

  1. intercept every action sent to the store in a custom Effect, and print the text (Intercepting action...) to the console without modifying the action. (The Effect, that handles this action, should work normally.)
  2. if the action (that was previously sent to the store) made its job (i.e. the corresponding Reducer made modifications on the store), I also want to "react" on this, and print another message (Got state from store.) on the console

I have 2 problems in my code:

  1. the texts appear in the wrong order (i.e. first "Got state from store", then "Intercepting action...", then "Got state from store" again).
  2. to intercept every action, I make an array of all of the actions, defined in the application, and call ofType() with this array. If a new action is implemented, I have to manually update this array. Is there a way to retrieve the registered actions directly from the store ?

Below is the code:

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) {}
}

Thank you for any advice.

Upvotes: 0

Views: 586

Answers (1)

timdeschryver
timdeschryver

Reputation: 15505

May I ask why you need this? To answer the question:

  1. AFAIK you can't do this. An action first reaches all reducers, and then it's handled by effects. If you want to register actions BEFORE they reach a reducer, take a look at meta reducers.

  2. To react to all actions in an effect, don't use the ofType operator, and simply subscribe to the Actions stream.

Upvotes: 1

Related Questions