0

I'm creating a helper function (in a separate file) that will retrieve a value from the ngrx store for me:

  getItem(id: string) {
    this.store.select(getItemFromId(id)).pipe(
      take(1)
    ).subscribe((item) => {
      console.log(item); // has correct value
      return item;
    });
  }

  const item = this.getItem(1); // undefined

But as you can see, when I call the function I always get undefined. I think it's since you can't return out of a subscription, but not totally sure. Any ideas how to modify this fn so it will return the correct value?

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94

1 Answers1

0

You can get the value only asyncronously, check below.

// get item function
getItem(id: string): Observable<any> {
    return this.store.select(getItemFromId(id)).pipe(
      take(1)
    );
}

// anywhere
this.getItem(1).subscribe((item) => {
   console.log(item); // this should output now the value
}); 
Roman Šimík
  • 830
  • 10
  • 24