0
votes

I have a function that selects an offer, but I need to check whether this offer is in the Observable array of offers$ first.

selectOffer(offer) {
    this.offers$.subscribe(items => {
      items.forEach(item => {
        if (item === offer) {
          // if offer is in offers$, DO...
        }
      });
    });
  }

How could I transform this to work with Rxjs operators (pipe, map, filter etc..)

3
What's wrong with what you have now? Or you want to have an Observable that emits true/false based on whether the item is in the array?martin
We'll need more code. What do you expect the selectOffer to return? What kind of observable is this.offer$.Poul Kruijt

3 Answers

1
votes

Try find operator

Emit the first item that passes predicate then complete.

selectOffer(offer) {
    this.offers$.pipe(find((item: any) => item === offer)).subscribe(items => {
        console.log("Offer is in the list")
    });
}
1
votes

You can use .map on observables

Try like this:

selectOffer(offer) {
  this.offers$.map(item => item.filter(x => x === offer));
}
0
votes

After trying several options, this one seemed the most effective for my case:

this.offers$
      .pipe(
        map(items =>
          items ? items.filter((item: any) => item === offer) : null)
      )
      .subscribe(item => { /* DO */ });