Sunil Ojha
Sunil Ojha

Reputation: 273

Combining Multiple @Select in NGXS

I have multiple @Selects in a component like this:

@Select(ItemState.getMode) mode: Observable<Item>;
@Select(QuestionState.SingleQuestion) question: Observable<Question>;
@Select(ItemState.getItemNames) itemNames: Observable<any>;
@Select(ItemState.getItemStepDetails) itemStepDetails: Observable<any>;

Now, I want to fetch the values in my ngOnInit() for all of them and assign them to some variables which I can use in my template. I don't want to use them directly using async as I need to manipulate them.

What is the best way to do it?

Upvotes: 4

Views: 3679

Answers (1)

Garth Mason
Garth Mason

Reputation: 8011

As the comments have mentioned, combineLatest is probably the operator you are looking for.

You can still use the async pipe in your template if you combine those source selector Observables into another stream via map rather than a number of variables defined in the component. e.g.

this.combinedStream$ = combinelatest(mode$, question$, itemName$, itemDetails$)
.pipe(
  map(([m, q, name, detail]) => {
    // Manipulate/project the 4 results into what you need
    return { .. };
});

Then in your template you can use combinedStream$ | async to access the manipulated form, and let the async pipe handle the subscription.

In terms of NGXS, if this combining of a number selectors becomes common and you want to reuse that combination across multiple components then you'd want to take a look at NGXS Joining Selectors, or Meta Selectors, and use those directly in the template as usual.

Upvotes: 7

Related Questions