L'ereditarietà dei dati genitore-figlio ng-2 è stata una difficoltà per me.
Quella che sembra che potrebbe essere una soluzione pratica funzionante è filtrare il mio array totale di dati in un array composto solo da dati figlio a cui fa riferimento un unico ID genitore. In altre parole: l'ereditarietà dei dati diventa il filtraggio dei dati in base a un ID genitore.
In un esempio concreto questo può assomigliare a: filtrare un array di libri per mostrare solo i libri con un determinato 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 è nuovo per me, ma penso di essere vicino a far funzionare le cose qui.
(Anche la sovrascrittura dell'array di libri originale potrebbe essere un'opzione, quindi l'utilizzo *ngFor="#book of books"
.)
EDIT Avvicinandosi, ma dando ancora un errore.
//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
OnInit
e aggiuntobooksByStoreID = Book[];
nel componente.