【发布时间】:2018-10-22 14:02:20
【问题描述】:
当我尝试将 ASYNC 数据从父组件传递到子组件时,我收到未定义的消息。
由于 ASYNC 数据,我想来自 parent 的数据尚未绑定到 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
}
【问题讨论】:
-
你有没有像这样
console.log(this.childdate)在子组件的ngOnInit中通过控制台尝试过 -
首先
Observable不订阅就不要获取数据。在 OnInit 上记录this.childdata。让我知道它是否未定义。 -
console.log(this.childdate)(在 OnInit 中)未定义。
-
添加 *ngIf 条件。
。从父组件获取值后会加载子组件。
标签: angular angular5 google-cloud-firestore