-1

Want to filter array of objects in Angular8 with Observable. Did it with @Pipe but client recommends to use Observable.

I have an array. Need to filter it with 3 different inputs given in the UI. Done this using the @Pipe like below.

<tr *ngFor="let d of data | filter : input1: input2: input3 >
    <td></td>
    <td></td>
    <td></td>
</tr>

But recommendation is to use observable. How can we do this?

frido
  • 13,065
  • 5
  • 42
  • 56
Gnik
  • 7,120
  • 20
  • 79
  • 129

1 Answers1

2

Client does mean:

You likely have a http request anywhere which fetches the data as an observable. Currently you likely subscribe to your observable which could be avoided with async pipe.

Without filter:

data$: Observable<Data> = this.myApiService.getData(); // do not subscribe here

<tr *ngFor="let d of data$ | async">
    <td></td>
    <td></td>
    <td></td>
</tr>

Now you want to filter this data. You can rxjs-pipe your unfiltered data.

data$: Observable<Data[]> = this.myApiService.getData(); // do not subscribe here
filteredData$: Observable<Data[]> = this.data$.pipe(
  map((data: Data[]) =>
    data.filter((entry: Data) =>
      /* your filter condition, where you check input 1-3 */
    )
  ),
);

<tr *ngFor="let d of filteredData$ | async">
    <td></td>
    <td></td>
    <td></td>
</tr>
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43