Przekazuję dane asynchroniczne z komponentu nadrzędnego do komponentu potomnego. A komponent potomny musi znać długość danych, aby coś zrobić.Angular 2, jak sprawić, by komponent potomny oczekiwał na gotowość danych asyn
Problem polega na tym, że komponent potomny nie może korzystać z haka "Oninit" w celu wykonywania pracy, ponieważ dane nie są obecnie dostępne. Więc jak mam to zrobić?
Kod składnikiem dominującym wygląda następująco:
@Component({
moduleId: module.id,
selector: 'parent',
template: `<div>
<child [items]="items | async">
</div>`
})
export class Parent implements OnInit {
items: Items[];
constructor(
private itemService: ItemService,
private router: Router
) { }
ngOnInit() {
this.itemService.getItemss()
.subscribe(
items => this.items = items,
error => this.errorMessage = <any>error
);
}
}
i składnik dziecko wygląda następująco:
@Component({
moduleId: module.id,
selector: 'child',
template: `<div>
<div *ngFor="let itemChunk of itemChunks"></div>
content here
</div>`
})
export class child implements OnInit{
@Input() items: Items[];
itemChunks: Items[][];
ngOnInit() {
this.itemChunks = this.chunk(this.Items);
}
chunk(items: Items[]) {
let result = [];
for (var i = 0, len = items.length; i < len; i += 6) { // this line causes the problem since 'items' is undefined
result.push(items.slice(i, i + 6));
}
return result;
}
}
jaka jest najlepsza praktyka, aby sobie z tym poradzić?
Skorzystaj z opcji 2. Zachowuje się dokładnie zgodnie z oczekiwaniami. Dziękuję bardzo. –
@Chybie, dzięki za skopiowanie mojej odpowiedzi: d – Milad
@Milad, przepraszam? Nie rozumiem cię. – Chybie