首页 文章

Angular Component Constructor被称为两次

提问于
浏览
8

我是Angular的新手,并且遇到了一个问题,一个子组件的构造函数被调用两次,第二次被调用它就是第一次清除属性集 .

这是父组件:

@Component({
    selector: 'parent-item',
    templateUrl: '...',
    providers: [ItemService]
})
export class ParentItemComponent {
    public parentItemId;
    public model: ParentItem;

    constructor(itemService: ItemService, elm: ElementRef) {
        this.parentItemId = elm.nativeElement.getAttribute('parentItemId'); 
        itemService.getParentItem(this.parentItemId).subscribe(data => this.model = data);
    }
}

在模板中引用了子组件:

<child-items [parentItemId]="parentItemId">Loading...</<child-items>

这是子组件:

@Component({
    selector: 'child-items',
    templateUrl: '...',
    providers: [ItemService]
})
export class ChildItemsComponent {
    @Input() public parentItemId: number;
    public items: Observable<ChildItem[]>;

    constructor(private itemService: ItemService) {
        console.log("constructor");
    }

    ngOnInit() {
        if (this.parentItemId) {
            this.items = this.itemService.getChildItems(this.parentItemId);
        }  
        else {
            console.log("Parent Id not set!");
        }
    }
}

最后是子组件模板:

<tr *ngFor="let item of items | async">
    <td>...</td>
</tr>

子组件构造函数被调用两次,第二次调用它时,parentItemId被设置为null并清除items属性 . 如果我对parentId进行硬编码而不是使用输入,则正确接收数据并在模板中显示,但使用输入值时,模板不会显示任何结果 .

我创建了一个在这里显示相同行为的plunker:http://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/

2 回答

  • 7

    child-items 未正确关闭 . 可能是因为this error

    这个

    <child-items [parentItemId]="parentItemId">Loading...</<child-items>
    

    应该:

    <child-items [parentItemId]="parentItemId">Loading...</child-items>
    
  • 1

    您的问题是,在app.module中,您可以引导父组件和子组件:

    bootstrap:    [ ParentItemComponent, ChildItemsComponent ]
    

    它一定要是

    bootstrap:    [ ParentItemComponent]
    

相关问题