如何在Angular 2中用TypeScript过滤数组?

对于我来说,ng-2亲子数据inheritance一直是个难题。

什么似乎可能是一个很好的工作实际的解决scheme是过滤我的数据总数组到一个由只有一个父id引用的子数据组成的数组。 换句话说:数据inheritance成为一个父ID的数据过滤。

在一个具体的例子中,这可以看起来像:过滤书籍数组,只显示具有特定store_id的书籍。

 import {Component, Input} from 'angular2/core'; export class Store { id: number; name: string; } export class Book { id: number; shop_id: number; title: string; } @Component({ selector: 'book', template:` <p>These books should have a label of the shop: {{shop.id}}:</p> <p *ngFor="#book of booksByShopID">{{book.title}}</p> ` ]) export class BookComponent { @Input() store: Store; public books = BOOKS; // "Error: books is not defined" // ( also doesn't work when books.filter is called like: this.books.filter // "Error: Cannot read property 'filter' of undefined" ) var booksByStoreID = books.filter(book => book.store_id === this.store.id) } var BOOKS: Book[] = [ { 'id': 1, 'store_id': 1, 'name': 'Dichtertje' }, { 'id': 2, 'store_id': 1, 'name': 'De uitvreter' }, { 'id': 3, 'store_id': 2, 'name': 'Titaantjes' } ]; 

TypeScript对我来说是新的,但我认为我接近于在这里工作。

(也可以覆盖原始书籍数组,然后使用*ngFor="#book of books"

编辑越来越近,但仍然给错误。

 //changes on top: import {Component, Input, OnInit} from 'angular2/core'; // ..omitted //changed component: export class BookComponent implements OnInit { @Input() store: Store; public books = BOOKS; // adding the data in a constructor needed for ngInit // "EXCEPTION: No provider for Array!" constructor( booksByStoreID: Book[]; ) {} ngOnInit() { this.booksByStoreID = this.books.filter( book => book.store_id === this.store.id); } } // ..omitted 

您需要将您的代码放入ngOnInit并使用this关键字:

 ngOnInit() { this.booksByStoreID = this.books.filter( book => book.store_id === this.store.id); } 

您需要ngOnInit因为inputstore不会被设置到构造函数中:

ngOnInit在第一次检查伪指令的数据绑定属性之后,以及在其任何子项被检查之前调用。 当指令被实例化时,它只被调用一次。

https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html

在你的代码中,书籍过滤是直接定义到类的内容…

你可以在这里检查一个Plunker例子中的示例filter

 filter() { let storeId = 1; this.bookFilteredList = this.bookList .filter((book: Book) => book.storeId === storeId); this.bookList = this.bookFilteredList; }