Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstracting selectors and action handlers from state

Tags:

angular

ngxs

I was wondering whether it's possible to abstract the @Selectors and/or the @Action handlers from the @State class to a separate file? As the state grows bigger and as the selectors more complex, I'd like to move them to a separate file to keep the state class cleaner. Is there any way to do that in NGXS?

Edit: for future reference, I got an answer on the NGXS slack channel and it is indeed possible. We can create a separate selector class where to store all our selectors, passing them the state of interest as an argument.

export class EntityStateSelectors {
  @Selector([EntityState])
  thing(state: EntityStateModel) {
    return state.thing;
  }
}

As of now I still haven't figured out how to do the same for the action handlers, but extracting the selectors to a separate file already cleaned up the state class a lot !

like image 638
Ale Avatar asked Aug 27 '18 10:08

Ale


1 Answers

You can have a separate file for your selectors and is highly recommended. You can create a file like app.selectors.ts with something like this:

export class AppSelectors {

  @Selector([AppState])
  static viewModel(state: AppStateModel) {
    // your selector logic here
  }

}

Then you can use normally in your components like this:

@Component({...})
export class AppComponent {
  @Select(AppSelectors.viewModel) vm$: Observable<ViewModel>;
}

This greatly reduces the size of your app.state.ts file since it leaves just the action handlers there. Also, this makes your code easier to test since your selectors are just pure functions

like image 146
Mateus Carniatto Avatar answered Nov 14 '22 16:11

Mateus Carniatto