在Angular中过滤组件数据

时间:2017-12-28 21:14:58

标签: angular angular-components

我的组件返回一个地方列表。现在,我希望能够根据特定类别过滤这些地方(吃饭,看看,睡觉......)。

我应该为过滤器功能创建一个新组件吗?我该如何过滤列表?

我的数据(json-server)如下所示:

[
  {
    "id": 1,
    "name": "Los Pollos Hermanos",
    "slug": "los-pollos-hermanos",
    "category": "eat",
    "address": "Street 21",
    "description": "Lorem ipsum",
    "top": true
  },
  {
    "id": 2,
    "name": "Savoy Wine Bar & Grill",
    "slug": "savoy-wine-bar-grill",
    "category": "see",
    "address": "Street 5",
    "description": "Lorem ipsum",
    "top": false
  }
]

从我的组件中提取:

  categories: string[] = ['eat', 'sleep'];

  constructor(private poiService: PoiService, private http: HttpClient) {}

  ngOnInit() {
    this.getPois();
  }

  getPois(): void {
    this.poiService.getPois().subscribe(pois => {
      this.pois = pois;
    });
  }

从我的component.html提取:

<nav>    
  <span *ngFor="let category of categories">
    <a routerLink='/category/{{category}}'>
      {{ category }}
    </a>
  </span>    
</nav>

<ul class="places">
  <li *ngFor="let poi of pois">
    <a routerLink='/detail/{{poi.slug}}'>
      <h3>{{poi.name}}</h3>
    </a>
  </li>
</ul>

从我的服务中提取:

  constructor(private http: HttpClient) {}

  getPois(): Observable<Poi[]> {
    return this.http.get<Poi[]>(API);
  }

2 个答案:

答案 0 :(得分:0)

您实际上不需要用于过滤数组的组件。你可以使用这样的东西

let seeArray = originalArray.filter(item => item.category === 'see');

答案 1 :(得分:0)

如果要在其他地方使用数据,根据复杂程度,您可能需要考虑获取/设置/存储数据的服务,但对于过滤,请记住Angular鼓励JS基础知识,在本例中为Array .filter:

let filteredPOIs = this.pois.filter(poi => poi.category === 'eat');