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

问题是子组件无法使用"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;
    }
}

处理此问题的最佳实践是什么?

推荐答案

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

  1. 在家长中打*ngIf分.仅当父对象的items准备好时才渲染子对象.
<div *ngIf="items">
   <child [items]="items | async">
</div>
  1. 在child中分离输入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);
    })
}
  1. 在子元素ngOnChanges岁的时候做.参考这里的例子.https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges

Angular相关问答推荐

如何在Angular模块中的forRoot中注入配置

Angular 16路卫单元测试可观察到的SpyObj属性

如何在Angular 17 SSR中处理Swiper 11 Web组件事件

在Cypress中,对xlsx文件的读取并不总是正确的

VS代码中带Angular 17的缩进新控制流

Angular 16模块中未使用的组件是否从Bundle 包中删除(树摇动)?

如何解决在StackBlitz中使用SPARTIER时出现无法解析解析器错误(&C)?

当信号的值发生变化时,模板不会更新

无法在 app.component.html 中呈现自定义组件

Angular Mat Select 显示键盘焦点和鼠标悬停焦点的问题

RxJS如何按顺序进行POST请求,只有在前一个完成后才会触发新的请求?

包含与 ngFor 相关内容的 HTML 输入

从 angular 11 升级到 angular 12 后,我的项目没有使用优化参数进行编译

在 Angular material表上调用 renderRows()

无法获得 angular-material md-sidenav 的 100% 高度

如何在angular 5 中获取基本网址?

无法从模块it was neither declared nor imported导出服务

Angular2 - 如何开始以及使用哪个 IDE

升级到 angular-6.x 会给出Uncaught ReferenceError: global is not defined

为什么 ngOnInit 被调用两次?