通过@ViewChild 获取异步数据

Get async data via @ViewChild

有一个 子组件 发出 API 请求并获取一些异步数据。此数据存储到 属性 count.

有一个 组件 Parent 需要在获取后获取 count 值并对其执行一些操作。

ParentComponent.ts

@ViewChild('child', {static: false}) child: ChildComponent;
...
ngAfterViewInit() {
    this.number = this.child.count;
}
...

问题

由于 count 属性 是异步的,在 ngAfterViewInit() 中我收到 undefined。如何获得更新值?也许 ngOnChanges() 或其他适合我的东西?

你得到未定义的原因是你期望在异步数据可用之前的值(我假设你的异步请求完成时)。您可以使用官方文档中的 Event Emitter to send the data to the parent. This way, you can set number in the parent to be the value of count only when you have it. I also recommend reading the Component Interaction 指南。

  1. 在您的子组件中注册事件发射器

子组件

@Output() countChanged: EventEmitter<any> = new EventEmitter();

  1. 收到数据后,可以将数据发送给父级:
// ...Logic that gets the data
this.countChanged.emit(this.count);
//...
  1. 在父模板中,您可以绑定到子组件并监听子事件。

父组件HTML

<child-component (countChanged)="doSomethingWithCount($event)></child-component>`

父组件

public doSomethingWithCount(count: number):void {
    this.number = count;
    //. . . More logic
}