我试图将动态数据传递给子组件.但我总是在子组件中获取未定义的数据.以下是我正在做的事情.
ParentComponent.ts
results: any[]; ngOnInit() { this.http.get('url').subscribe(data => this.results = data); }
ParentComponent.html
<app-childComponent [dataneeded]=results></app-childComponent>
ChildComponent.ts
@Input('dataneeded') dataneeded: any[]; ngOnInit() { console.log(dataneeded); //Always undefiend }
正如预期的那样,它不会等待异步调用并返回undefined.如何将动态数据传递给组件?
解决方法
问题是UI线程将在可观察完成的订阅之前呈现子组件.
你需要这样做:
import { ChangeDetectorRef } from '@angular/core'; constructor(private ref: ChangeDetectorRef) {} ngOnInit() { this.http.get('url').subscribe(data => { this.results = data; this.ref.markForCheck(); }); }
在HTML中,您必须首先测试该值.
<ng-container *ngIf="results != null"> <app-childComponent [dataneeded]=results></app-childComponent> </ng-container>
稍微说明一下,.markForCheck()
将在订阅后刷新结果,并通知所有使用此“值”的组件更新其值,包括ng-container.容器现在允许渲染子组件,这将保证当子进行其生命周期时结果不为null.