11

我是 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/

4

2 回答 2

9

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

bootstrap:    [ ParentItemComponent, ChildItemsComponent ]

它一定要是

  bootstrap:    [ ParentItemComponent]
于 2016-11-21T22:13:30.360 回答
2

child-items没有正确关闭。可能是因为这个错误

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

应该:

<child-items [parentItemId]="parentItemId">Loading...</child-items>
于 2018-07-19T12:08:08.027 回答