【问题标题】:How can I filter array with multiple criteria in Angular8 using Observable?如何使用 Observable 在 Angular8 中过滤具有多个条件的数组?
【发布时间】:2020-01-07 05:58:46
【问题描述】:

想用 Observable 过滤 Angular8 中的对象数组。用@Pipe 做的,但客户建议使用 Observable。

我有一个数组。需要使用 UI 中给出的 3 个不同的输入对其进行过滤。 使用下面的@Pipe 完成此操作。

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

但建议使用 observable。我们该怎么做?

【问题讨论】:

  • 您可以添加您尝试过的代码吗?
  • data的内容是什么?也将其发布在问题中..

标签: angular rxjs rxjs6 angular8 angular2-observables


【解决方案1】:

客户的意思是:

您可能在任何地方都有一个 http 请求,它将数据作为 observable 获取。目前您可能订阅了您的 observable,这可以通过异步管道来避免。

没有过滤器:

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

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

现在您要过滤此数据。您可以 rxjs-pipe 未过滤的数据。

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>

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2019-03-02
    • 2021-11-20
    • 2023-01-07
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多