【问题标题】:Angular Component Constructor Called TwiceAngular 组件构造函数被调用两次
【发布时间】:2017-04-02 16:10:01
【问题描述】:

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

【问题讨论】:

  • &lt;child-items [parentItemId]="parentItemId"&gt;Loading...&lt;/&lt;child-items&gt;&lt;/&lt; 故意这样做的吗?

标签: javascript angular html typescript angular-components


【解决方案1】:

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

bootstrap:    [ ParentItemComponent, ChildItemsComponent ]

必须是

  bootstrap:    [ ParentItemComponent]

【讨论】:

  • 我在main.tsapp.module.ts 中都使用了platformBrowserDynamic().bootstrapModule(AppModule)。从app.module.ts 中删除该行使其适用于我的情况。
【解决方案2】:

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

这个

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

应该是:

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

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2019-07-05
    • 2012-06-11
    • 2019-12-02
    • 1970-01-01
    • 2013-12-11
    • 2014-07-28
    • 2011-02-12
    相关资源
    最近更新 更多