Angular 2如何使子组件等待异步数据准备好 [英] Angular 2 how to make child component wait for async data to be ready
本文介绍了Angular 2如何使子组件等待异步数据准备好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将异步数据从父组件传递到子组件.而且子组件需要知道数据的长度才能执行某些操作.
I'm passing async data from a parent component to a child component. And the child component needs to know the length of the data in order to do something.
问题是子组件不能使用'Oninit'钩子来完成工作,因为此时数据不可用.那我该怎么办呢?
How the problem is that the child component can't use the 'Oninit' hook to do work because the data isn't available at this time. So how do I do this?
父组件代码如下:
@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
);
}
}
子组件看起来像:
@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;
}
}
处理此问题的最佳做法是什么?
What is the best practice to handle this?
推荐答案
有三种方法可以做到这一点:
There are three ways to do this:
- 在父级中放置一个
*ngIf
.仅在父母的items
准备就绪时渲染孩子.
- Put an
*ngIf
in parent. Only render child when parent'sitems
is ready.
<div *ngIf="items">
<child [items]="items | async">
</div>
- 在子级中分隔输入
getter
setter
.然后,只要设置了该值,就执行操作,也可以使用RxJSBehaviorSubject
.
- Separate your input
getter
setter
in child. Then act whenever the value is set, you can use RxJSBehaviorSubject
also.
private _items = new BehaviorSubject<Items[]>([]);
@Input() set items(value: Items[]) {
this._items.next(value);
}
get items() {
return this._items.getValue();
}
ngOnInit() {
this._items.subscribe(x => {
this.chunk(x);
})
}
- 在孩子的
ngOnChanges
期间进行.例如,请参考这里. https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges
- Do it during the
ngOnChanges
of the child. Refer to here for example. https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges
这篇关于Angular 2如何使子组件等待异步数据准备好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文