Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current value of ngrx selector without subscription

I have my ngrx state this way

state.data state.dataArchived

I would like to copy data from store.data to state.dataArchived.

selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch));
ngOnInit() {
  this.store.dispatch(new GetDirectionsOnGraph({}));
  this.selectedSchedulingsOnPopup$.subscribe(value => {
    this.selectedSchedulingsOnPopupValue = value;
    this.store.dispatch(new GetDirectionsOnGraph(this.selectedSchedulingsOnPopupValue));
  });
}

the problem is when state.data changes, state.dataArchived changes too

So I would like to get the current value of state.data without subscribing to it.

like image 796
infodev Avatar asked Dec 18 '22 14:12

infodev


1 Answers

I don't understand the question, but if you want to get the value without subscribing to it, you can convert it into a promise.

async ngOnInit() {
  const data = await this.store.pipe(select(selectorForData),
                               take(1)).toPromise();
}

Keep in mind, that in this promise way, it will only react once and get the data and carry on. If you want to be informed of the changes of the data slice, you have to subscribe to it, there is no other way around it.

toPromise is marked as deprecated now. You can use lastValueFrom to transform observable into promise as below.

async ngOnInit() {
      const data = await lastValueFrom(this.store.pipe(select(selectorForData),
                                   take(1)));
}
like image 123
AliF50 Avatar answered Dec 20 '22 03:12

AliF50