[英]Angular Component Constructor Called Twice
I am new to Angular and am running into an issue with the constructor on a child component being called twice, and the second time it is called it is clearing the properties set the first time. 我是Angular的新手,并且遇到了一个问题,一个子组件的构造函数被调用两次,第二次被调用它就是第一次清除属性集。
This is the parent component: 这是父组件:
@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);
}
}
And in the template the child component is referenced: 在模板中引用了子组件:
<child-items [parentItemId]="parentItemId">Loading...</<child-items>
This is the child component: 这是子组件:
@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!");
}
}
}
And finally the child component template: 最后是子组件模板:
<tr *ngFor="let item of items | async">
<td>...</td>
</tr>
The child components constructor is being called twice, and the second time it is called the parentItemId is set to null and the items property is cleared. 子组件构造函数被调用两次,第二次调用它时,parentItemId被设置为null并清除items属性。 If I hardcode the parentId instead of using the input the data is being properly received and displayed in the template, but using the input value the template shows no results. 如果我对parentId进行硬编码而不是使用输入,则正确接收数据并在模板中显示,但使用输入值时,模板不会显示任何结果。
I have created a plunker which shows the same behavior here: http://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/ 我创建了一个在这里显示相同行为的plunker: http ://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/
Your problem is that in the app.module you bootstrap both parent and child component: 您的问题是,在app.module中,您可以引导父组件和子组件:
bootstrap: [ ParentItemComponent, ChildItemsComponent ]
It has to be 它一定要是
bootstrap: [ ParentItemComponent]
child-items
is not closed properly. child-items
未正确关闭。 Probably because of this error 可能是因为这个错误
This 这个
<child-items [parentItemId]="parentItemId">Loading...</<child-items>
should be: 应该:
<child-items [parentItemId]="parentItemId">Loading...</child-items>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.