私はAngularを初めて使用し、子コンポーネントのコンストラクターが2回呼び出されるという問題に遭遇しています。2回目に呼び出されると、最初に設定されたプロパティがクリアされます。
これは親コンポーネントです:
@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>
子コンポーネント コンストラクターが 2 回呼び出されており、2 回目に呼び出されたときに、parentItemId が null に設定され、items プロパティがクリアされます。入力を使用する代わりにparentIdをハードコードすると、データは適切に受信されてテンプレートに表示されますが、入力値を使用するとテンプレートに結果が表示されません。
ここで同じ動作を示すプランカーを作成しました: http://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/