kovac
kovac

Reputation: 5389

Observable array is empty in ngrx

I have a an observable array that binds to a data grid in the html and this is working fine. My component.ts gets the array like:

this.data = this.store.pipe(select(selectData));

where selectData is an ngrx action. I'm trying to set the value of an input outside the data grid based on the first value in the data array. I'm trying something like

this.input= this.data.pipe(map(m => 
      moment(new Date(m[0].timestamp / 1000000)).format('DD-MM-YYYY HH:mm:ss')));

When I'm debugging this, I can see the break point on the line with moment(new Date... hitting. However, the m at this time is an empty array. Both of the above statements are declared in ngOnInit like

ngOnInit(): void {
    this.data = this.store.pipe(select(selectData));
    this.input= this.data.pipe(map(m => 
      moment(new Date(m[0].timestamp / 1000000)).format('DD-MM-YYYY HH:mm:ss')));
  }

It looks like the observable is resolved before the array is actually populated causing the input to be undefined. How can I make sure that the this.data array is actually fully populated by the time I try to set the this.input?

Upvotes: 1

Views: 510

Answers (1)

Nicholas K
Nicholas K

Reputation: 15433

You need to subscribe in order for the selector to pick up data from the store. Make the following change:

ngOnInit(): void {
   this.store.pipe(select(selectData))
      .subscribe(m => {
         this.input = moment(new Date(m[0].timestamp / 1000000))
                          .format('DD-MM-YYYY HH:mm:ss');
      });
}

Upvotes: 1

Related Questions