Search code examples
angularngrxngrx-effectsside-effects

Triggering side-effects outside the ngrx store via component output


I have a module with a modal in which I do some form work, the modal has it's tiny feature store.

When I finish my work (trigger: a successful save), I need to fire an output event, so that my context (the component that wraps my modal) can close the modal. I cannot go via a classic action - the context is not aware of my actions, and can only respond to an Output on my component.

So what I have is now this:

@Component MyComponent {
  @Output() closeModal = new EventEmitter();
  constructor(private store: Store<MyState>, private actions: Actions) {
    // Here I subscribe to actions. Is there another way to do this?
    this.actions.pipe(
      ofType(actionTypes.SaveSuccess),
      tap(() => this.closeModal.emit(),
    );
  }
}

Is there a better way to do this? importing actions stream to a component seems wrong, and I would like to avoid having to add new keys to my state interface just for this.

Edit: To clarify, I want to fire an Output event on my Component based on some ngrx action.


Solution

  • Listening to the actions stream within a component does have a use-case. It might feel weird at the beginning, but I don't see nothing wrong it. We're also going to add an example of this in the ngrx.io docs - see the issue on GitHub.

    In the future you could use @ngrx/component for it.

    I use @ngrx/effects to handle dialog flows, but I'm not sure if it fits your use case. See Start using ngrx/effects for this for an example and more info on how to do it.