数组 – 如何使用角度2中的TypeScript过滤数组?
ng-2亲子数据继承对我而言是一个困难.
什么似乎是一个很好的工作实际的解决方案是将我的总数据数据过滤到仅由单个父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': '/url/vector_a' },{ 'id': 2,'name': '/url/vector_b' },{ 'id': 3,'store_id': 2,'name': '/url/vector_c' } ]; TypeScript对我来说是新的,但我认为我很接近使事情在这里工作. (也可以覆盖原书数组,可以是一个选项,然后使用* ngFor =“#书籍簿”.) 编辑 //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( booksByAimID: Book[]; ) {} ngOnInit() { this.booksByAimID = this.books.filter( book => book.store_id === this.store.id); } } // ..omitted
您需要将代码放入ngOnInit并使用此关键字:
ngOnInit() { this.booksByStoreID = this.books.filter( book => book.store_id === this.store.id); } 您需要ngOnInit,因为输入存储将不会被设置到构造函数中:
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html) 在你的代码中,图书过滤直接定义到类内容中 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |