ng-2 pewarisan data orang tua-anak telah menjadi kesulitan bagi saya.
Apa yang tampaknya bisa menjadi solusi praktis yang berfungsi dengan baik adalah memfilter total array data saya ke array yang hanya terdiri dari data anak yang direferensikan oleh id orang tua tunggal. Dengan kata lain: data-inheritance menjadi pemfilteran data oleh satu id induk.
Dalam contoh konkret ini dapat terlihat seperti: memfilter larik buku untuk hanya menampilkan buku dengan yang tertentu 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 baru bagi saya, tetapi saya pikir saya hampir membuat semuanya berfungsi di sini.
(Juga menimpa larik buku asli bisa menjadi opsi, lalu menggunakan *ngFor="#book of books"
.)
EDIT Semakin dekat, namun tetap memberikan error.
//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
sumber
OnInit
dan menambahkanbooksByStoreID = Book[];
komponen.booksByStoreID: Book[];
]
Anda dapat memeriksa contoh di Plunker di sini contoh filter plunker
sumber
Untuk memfilter larik terlepas dari jenis properti (yaitu untuk semua jenis properti), kita dapat membuat pipa filter kustom
Jangan lupa untuk mengimpor pipa di modul aplikasi
Kita mungkin perlu menyesuaikan logika ke filer dengan tanggal.
sumber