Angular组件构造函数被调用两次
Angular Component Constructor Called Twice
我是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>
相关文章:
- Meteor Router数据函数被调用两次
- Backbone.js ListenToOnce被调用两次
- 当我的单元测试失败时,回调被调用了两次
- 我的jQuery加载请求是否被调用了两次
- 为什么DTM数据元素被调用两次
- jQuery 方法调用了两次
- 模态中的数据关闭在单击时被调用两次
- 调用一个函数两次
- java-script 函数被调用两次
- 查找与通过两次调用地理编码创建的两个 latlng 对象的距离
- Primefaces:RequestContext.execute-调用了两次Javascript
- 在一个页面中包含两次的脚本中调用函数
- 调用随机函数Javascript,但不能两次调用相同的函数
- 如何防止在快速单击时两次调用en事件处理程序
- 在AngularJS中,一次进行两次调用是一种可接受的方法
- jquery停止两次调用委派事件
- 我没有'我不想两次调用自定义函数
- Javascript:两次调用函数会导致不必要的行为
- 当两次调用一个方法时,仅呈现一个SVG组件
- JavaScript在两次调用之间占用额外时间