当我尝试将ASYNC数据从父组件传递到子组件时,我收到了未定义的消息 .
由于ASYNC数据,我认为来自父节点的数据尚未绑定在OnInit上 .
在parent.component.html中:
<my-child [childdata]="parentdata"></my-child>
在parent.component.ts中:
interface SpotBB {
id: number;
name: string;
}
...
export class ParentComponent implements OnInit {
parentdata: Observable<SpotBB[]>;
...
ngOnInit() {
this.parentdata = this.spotsservice.getSpots();
// Call a service - Data stored in Firestore
}
在child.component.html中:
<button (click)="mycheck()">TEST</button>
<div *ngFor="let spot of childdata | async" >
{{ spot.id }} --- {{ spot.name }} <!-- Works fine -->
</div>
在child.component.ts中:
interface SpotBB {
id: number;
name: string;
}
...
export class ChildComponent implements OnInit {
@Input() childdata: Observable<SpotBB[]>;
copydata: Observable<SpotBB[]>;
...
mycheck() {
alert(JSON.stringify(this.copydata)); // --> !!! undefined !!!
}
ngOnInit() {
this.copydata = this.childdata; // COPY DATA NOT WORKING
}
2 回答
而不是@Input()childData,@ Input()设置childData将起作用 . 这将使childData在更改时刷新 .
您可以实现几个选项来实现它:
1.使用
ngOnChanges
侦听更改子组件中的@Input:2.在
childdata
的子组件中使用set
:3.只有在
parentdata
可用后才能使子组件可用(如果可以接受):父组件html:
在parent.component.ts中:
对于所有选项,我猜测订阅
getSpots
,在您的父组件中接收parentdata
并分配给this.parentdata
: