Search code examples
angularrxjsngrx

What is the correct way to read from NgRx store using selector in an angular service and use the value to call another function?


I have an NgRx selector defined like this

selectedRows = createSelector(
    someState,
    state => state[fromDataSource.someSliceKey].selectedRows);

Whenever some items are selected on a component (UI), selectedRows gets updated with latest selected items. Now there is another button on another component which calls an angular service to perform some operation which eventually calls bunch of an external APIs. I would like to read the values stored in selectedRows using the above defined selector on the angular service and make those API calls.

What is the correct way to do this?

One of the approach I am considering is to subscribe to the selector something like this:

const selectedRows$ = this.store.pipe(
  select(fromSelectors.selectedRows)
  ).subscribe(data => {
  // call other functions and dispatch actions to call external API
});

Since I am calling subscribe here how do I unsubscribe? Is there way to do this without having to call subscribe?

Update: Found another similar question - How to dispatch an action with current value of state?


Solution

  • This seems to be a good use case for NgRx Effects:

    myEffects$ = createEffect(
      () => actions$.pipe(
        ofType(actionDispatchedWhenButtonPressed)
        withLatestFrom(this.store.pipe(select(selectedRows))),
        switchMap(([action, selectedRows]) => /* ...API calls... */)
      )
    )