Javascript 角度分量构造函数调用了两次

Javascript 角度分量构造函数调用了两次,javascript,angular,html,typescript,angular-components,Javascript,Angular,Html,Typescript,Angular Components,我是Angular的新手,遇到了一个问题,子组件上的构造函数被调用了两次,第二次调用时,第一次清除了属性集 这是父组件: @Component({ selector: 'parent-item', templateUrl: '...', providers: [ItemService] }) export class ParentItemComponent { public parentItemId; public model: ParentItem;

我是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);
    }
}
@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!");
        }
    }
}
bootstrap:    [ ParentItemComponent, ChildItemsComponent ]
在模板中引用子组件:

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

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

@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);
    }
}
@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!");
        }
    }
}
bootstrap:    [ ParentItemComponent, ChildItemsComponent ]
一定是这样

  bootstrap:    [ ParentItemComponent]

子项
未正确关闭。可能是因为

这个


加载…
加载…我在
main.ts
app.module.ts
中都使用了
platformBrowserDynamic().bootstrapModule(AppModule)
。从
app.module.ts
中删除该行使其在我的情况下工作。