Search code examples
angularngxs

Using ngxs Selectors in Components


I am using ngxs with Angular and right now when I am trying to fetch changes from the store I define a selector in the state

@Selector()
static getData(state : DataStateModel){
    return state.data;
}

and in the component I use the @Select decorator to get an observable

@Select(DataState.getData) data$;

The trouble I am having is that if I have to access this data in the component, I will subscribe to the data$ observable and save the data to a new variable in the component.

ngOnInit() {
    this.datasubscription = this.data$.subscribe( data => {this.componentVar = data});
}

This requires me to manually unsubscribe. Is this the correct way to implement this? Are there any inbuilt functions or third party plugins that can help cleanup this part? I have also tried.

store.snapshot()

Solution

  • If you don't want to manage a subscription in the component code you could use the Observable from the Select decorator to compose a new Observable chain e.g. in this example dataChanged$. In this observable via the rxjs tap operator you could run some validation or toggle a variable etc as you described in the comments.

    @Select(DataState.getData) data$;
    
    dataChanged$: Observable<any>;
    
    ngOnInit() { 
    
     this.dataChanged$ = this.data$.pipe(
        tap(result => // do something)
     );
    }
    

    Then in your template, subscribe to $dataChanged via the async pipe.

    The other option of course is to manually unsubscribe when ngOnDestroy is called for this component.