Angular组件构造函数被调用两次

Angular Component Constructor Called Twice

本文关键字:两次 调用 组件 构造函数 Angular      更新时间:2023-09-26

我是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而不是使用输入,则数据将被正确接收并显示在模板中,但使用输入值,则模板没有显示结果。

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

你的问题是在app.module中你引导父组件和子组件:

bootstrap:    [ ParentItemComponent, ChildItemsComponent ]

必须是

  bootstrap:    [ ParentItemComponent]

child-items未正常关闭。可能是因为这个错误

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

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