Search code examples
angulartypescriptrxjs-pipeable-operators

why the argument from filter operator is not taking a property that exist in the observable array


I'm trying to filter an array that comes from an observable if the property "start" which is a date string match with another date string, but within the filter operator function the argument is not recognizing "start" as a valid property

I have read multiple examples and comparing to mine seems to be a very similar scenario

export class AuctionsService() {

private _auctions = new BehaviorSubject(
    [
      {
        idAuction: '1',
        start: '2019-07-18T15:30',
      },
      {
        idAuction: '2',
        start: '2019-07-18T15:30',
      },
      {
        idAuction: '3',
        start: '2019-07-18T15:30',
      },
      {
        idAuction: '4',
        start: '2019-07-19T15:30',
      },
    ]
  );
 get auctions() {
    return this._auctions.asObservable();
  }
}

On another file when I'm subscribing to this observable

    selectedDate = '2019-07-19T12:46';

  constructor(
    private auctionsService: AuctionsService,
  ) { }

      ngOnInit() {
        this.auctionsService.auctions.pipe(filter(
          aucs => aucs.start.slice(0, 10) === this.selectedDate.slice(0, 10)
        )).subscribe(
          aucs => { this.auctions = aucs; }
        );
      }

Expected output should be: { idAuction: '4', start: '2019-07-19T15:30', },

but is not compiling it states .start is not a valid property of aucs


Solution

  • As @dcg said, aucs as returned from the this.auctionsService.auctions observable is an array, but your code was treating it as if it was an element from an array. So you need to filter it as an array:

    ngOnInit() {
      this.auctionsService.auctions.pipe(
        map(
          aucs => aucs.filter(auc => auc.start === this.selectedDate;
          )
        )
      ).subscribe(aucs => {
        this.auctions = aucs;
      });
    }