Search code examples
ngxs

Reuse selector in other selectors in NGXS


I have two classes PizzasState and ToppingsState. PizzaState already has selector to get selected pizza.

@State<PizzaStateModel>({
  name: 'pizzas',
  defaults: initialState
})
export class PizzasState {
  constructor(private pizzaService: PizzasService) {
  }

  @Selector([RouterState])
  static getSelectedPizza(
    state: PizzaStateModel,
    routerState: RouterStateModel<RouterStateParams>
  ): Pizza {
    const pizzaId = routerState.state && routerState.state.params.pizzaId;
    return pizzaId && state.entities[pizzaId];
  }

  @Selector()
  getPizzaVisualized(state: PizzaStateModel): Pizza {
    //
    // what is here?
    //
  }
}

and ToppingsState has selectedToppings

@State({
  name: 'toppings',
  defaults: initialState
})
export class ToppingsState {
  constructor(private toppingsService: ToppingsService) {
  }

  @Selector()
  static selectedToppings(state: ToppingsStateModel): number[] {
    return state.selectedToppings;
  }

Now I want to join my selected pizza with selected toppings and get my visualized pizza.

How can I reuse getSelectedPizza and getSelectedToppings correctly? Thank you


Solution

  • It looks like you need to use a joining selector.

    @Selector([ToppingsState.selectedToppings])
    getPizzaVisualized(state: PizzaStateModel, selectedToppings: number[]): Pizza {
        // User data from both states.
    }