Angular 2如何使子组件等待asyn数据准备就绪

时间:2016-12-30 00:38:29

标签: angular

我将异步数据从父组件传递到子组件。并且子组件需要知道数据的长度才能执行某些操作。

问题是子组件无法使用'Oninit'挂钩来工作,因为此时数据不可用。那我该怎么做呢?

父组件代码如下所示:

@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;
    }
}

处理此问题的最佳做法是什么?

3 个答案:

答案 0 :(得分:39)

有三种方法可以做到这一点:

  1. *ngIf放入父级。只有当父母items准备好后才会呈现孩子。

    <div *ngIf="items">
       <child [items]="items | async">
    </div>
    
  2. 将您的输入getter setter与儿童分开。然后,只要设置了值,就可以使用RxJS BehaviorSubject

    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);
        })
    }
    
  3. 在孩子的ngOnChanges期间执行此操作。例如,请参阅此处。 https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges

答案 1 :(得分:3)

更简单的解决方案:

ngOnChanges(changes: SimpleChanges) {
    if (changes['items'].currentValue) {
        this.items = items
    }
}

答案 2 :(得分:1)

您可以使用setter:

export class child implements OnInit{
    itemChunks: Items[][];

    private _items ;

    //bellow  will get called when ever the items are passed in by the parent component
    @Input( 'items' ) set items ( items: Items[] ) {
       this._items = items;

       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;
    }
}

顺便说一句,我觉得你的父组件也不对,它应该是:

@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
    ) { 
         this.items = this.itemService.getItemss(); // if getItemss is returning an observable, which I think it does
     }    

}