簡體   English   中英

Angular Component Constructor被稱為兩次

[英]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進行硬編碼而不是使用輸入,則正確接收數據並在模板中顯示,但使用輸入值時,模板不會顯示任何結果。

我創建了一個在這里顯示相同行為的plunker: 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM