Angular Component Constructor被称为两次

rwd*_*ial 9 javascript html5 typescript angular-components angular

我是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在模板中引用了子组件:

<child-items [parentItemId]="parentItemId">Loading...</<child-items>
Run Code Online (Sandbox Code Playgroud)

这是子组件:

@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!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后是子组件模板:

<tr *ngFor="let item of items | async">
    <td>...</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

子组件构造函数被调用两次,第二次调用它时,parentItemId被设置为null并清除items属性.如果我对parentId进行硬编码而不是使用输入,则正确接收数据并在模板中显示,但使用输入值时,模板不会显示任何结果.

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

Yak*_*ain 9

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

bootstrap:    [ ParentItemComponent, ChildItemsComponent ]
Run Code Online (Sandbox Code Playgroud)

它一定要是

  bootstrap:    [ ParentItemComponent]
Run Code Online (Sandbox Code Playgroud)

  • 我在main.ts和app.module.ts中都使用了platformBrowserDynamic()。bootstrapModule(AppModule)。从“ app.module.ts”中删除该行使其在我的情况下起作用。 (2认同)