在 angular 中的组件中显示之前过滤数据 5

Filter data before displaying in the component in angular 5

我有一份来自 api 的足球数据列表。

当我请求此 api 端点时,会显示所有可用列表。我试图根据游戏的状态分开列表。例如。已完成,已推迟,已限时。

我试过这样的东西

<div *ngFor="let fixture of fixtures">
    <div *ngIf="fixture.status !== 'FINISHED'">
        <p>{{fixture.date}}</p>
    </div>
</div>

它被过滤并且没有显示在视图中,但它没有被完全过滤。现在的问题是,由于列表太长,我只想显示前 20 个项目,我正在做如下:

<div *ngFor="let fixture of fixtures | slice:0:20">
    <div *ngIf="fixture.status !== 'FINISHED'">
        <p>{{fixture.date}}</p>
    </div>
</div>

因为它应该只显示过滤项目列表中的前 20 个项目,但它没有。它不显示任何列表,因为该列表仍然存在且未被过滤。

现在我觉得我现在的过滤方式不对。因为它只在视图中过滤,而不在来自 api 的列表中过滤,所以当我尝试对列表进行切片时,它不会像这样工作。

如果你们可以帮助我实现这一点,请告诉我。提前致谢。

不要那样使用slice管道,它不能与您的*ngIf一起使用;它对过滤后的结果集一无所知,只知道原始列表。

在我给出解决方案之前,先看看 slice 管道的源代码,看看它在你的列表中是如何工作的:

@Pipe({name: 'slice', pure: false})
export class SlicePipe implements PipeTransform {
  transform(value: any, start: number, end?: number): any {
    if (value == null) return value;

    if (!this.supports(value)) {
      throw invalidPipeArgumentError(SlicePipe, value);
    }

    return value.slice(start, end);
  }

  private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); }
}

如您所见,它接收原始列表(在本例中为过滤后的结果集),然后对其进行切片。

来源:Angular.io


要解决您的问题,请在组件中进行过滤,然后在模板中循环过滤结果。然后并且只有在那时你才应该应用 slice 管道。

这样效率更高(因为您不会在组件中进行不必要的循环),并且允许您对过滤列表进行 运行 更多操作,因为您已经缓存了它们。

分量:

@Component({...})
export class MyComponent {
    list: any[] = [...];
    fixtures: any[] = this.list.filter(item => item.status !== 'FINISHED');
}

模板:

<div *ngFor="let fixture of fixtures | slice:0:20">
    <p>{{fixture.date}}</p>
</div>

更新:

要解决您的搜索问题,请搜索原始列表,而不是过滤后的列表。