最佳答案
Ng-2父子数据继承对我来说一直是个难题。
看起来可能是一个很好的实用解决方案,就是将我的数据总数组过滤到一个由单个父 ID 引用的唯一子数据组成的数组中。 换句话说: 数据继承变成了一个父 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