Search code examples
javascriptangularreduxrxjsngrx

Typing issue pass selector to dispatched action as parameter


I would like to dispatch an action when as selector changes value. so I passe the selector with a subscription to avoid passing an observable

selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch));

this.store.dispatch(new GetDirectionsOnGraph(this.selectedSchedulingsOnPopup$.subscribe()))

I get this error

(property) BranchKpisComponent.selectedSchedulingsOnPopup$: Observable<ISchedules>
Argument of type 'Subscription' is not assignable to parameter of type 'ISchedules'.
  Index signature is missing in type 'Subscription'.

Solution

  • The whole code is not correct

    this this.selectedSchedulingsOnPopup$.subscribe() will return a subscription, not the value

    also each time you dispatch an action, you create a new subscription, which will result to unexpected behavior and memory leak

    you can separately subscribe to this one time (in ngOnInit for example)

    this.selectedSchedulingsOnPopup$
    .subscribe(value => {
      this.selectedSchedulingsOnPopupValue = value;
    })
    

    then later

    this.store.dispatch(new GetDirectionsOnGraph(this.selectedSchedulingsOnPopupValue))
    

    Note: Don't forget to unsubscribe from this.selectedSchedulingsOnPopup$ otherwise it will case memory leak