4

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.

infodev
  • 4,673
  • 17
  • 65
  • 138
  • Do you only need the first value that is returned by `selectedSchedulingsOnPopup`? – wentjun Jan 06 '20 at 18:33
  • I need the value when the component is rendered, so I suppose that is the first value when subscribe, and only the first value – infodev Jan 06 '20 at 21:50
  • Ahh... In that case this is similar to a question I have previously answered (https://stackoverflow.com/a/59419097/10959940). Let me know if it makes sense? If it still doesn't, I will provide an answer – wentjun Jan 07 '20 at 00:24
  • Does this answer your question? [NgRx Get value without subscribing](https://stackoverflow.com/questions/59296040/ngrx-get-value-without-subscribing) – James D Jan 07 '20 at 09:50

2 Answers2

11

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 firstValueFrom or lastValueFrom/take(1) to transform observable into promise as below.

async ngOnInit() {
      // firstValueFrom
      const data = await firstValueFrom(this.store.pipe(select(selectorForData));
      // lastValueFrom with take(1)
      const data = await lastValueFrom(this.store.pipe(select(selectorForData),
                                   take(1)));
}
AliF50
  • 16,947
  • 1
  • 21
  • 37
  • What I want is getting the current value of data when component is rendered , then if state.data changes ignore the new values , I think as you say by converting it to promise – infodev Jan 06 '20 at 18:01
3

If you just want the first value and then to ignore all subsequent changes use the first() operator:

  ngOnInit() {
    this.store.dispatch(new GetDirectionsOnGraph({}));
    this.selectedSchedulingsOnPopup$.pipe(first())
      .subscribe(value => {
        this.selectedSchedulingsOnPopupValue = value;
        this.store.dispatch(new GetDirectionsOnGraph(this.selectedSchedulingsOnPopupValue));
      });
  }
The Observer
  • 170
  • 12