0
votes

Is it possible to add new properties to an action with an action creator function that is reusable?

Actions in NGRX have the type property. I want to extend Actions to add a new property (Called customType) to all of my actions throughout my project. Basically I want to be able to listen in an effect for all actions that then have that property (Let's say action.customType === 'HTTP') with the idea to be able to have a single feature module that can keep track of the loading & error state of HTTP calls that is tied back to the action.

With goal to essentially be able to do this in a component:

this.store.dispatch(action.loadObject());
this.isLoading$ = this.store(httpSelectors.isLoading).pipe(x => x(action.loadObject))
1
I have doubts this is a good approach. You’d be polluting your Actions with stuff that really do not belong in an action. Plus, I see you’re planning a selector for this to figure out the loading state, which means you’d also have to pollute a lot of reducers to set this state in the store.. which is also not ideal. Why not simply have an effect to listens to all your relevant actions and have that trigger a loading ‘thing’ (service?). That would keep it clean and much simpler. - MikeOne
I could definitely do that, it's just we've got around 680 actions and I'm not sure I want to have to an effect that has an explicit listener for ~500 for those HTTP loading/success/failure actions. I'd prefer if I could to define it as part of the creationAction call - anewtonlevey

1 Answers

0
votes

I think you should/can use ActionsSubject, with it you will be able to listen to all actions.

constructor(
    private actions$: ActionsSubject
) {}

ngOnInit() {
    this.actions$.pipe(
        filter(action => action.customType === 'errorOrSomethingElse')
    ).subscribe(action => console.log(action));
}