如何在Angular中将异步数据返回从Observable from Child传递给Parent组件

问题描述

我正在尝试将异步数据从子组件传递到父组件。但是在console.log(this.values)内的ngAfterViewInit()中,父组件html页面加载中的值为空。但是,如果我在子组件中单击“应用”按钮,它将发出console.log(this.values);方法内部的getValues($event)打印事件。

这是我的父组件.ts文件

name = 'ViewUI';
@ViewChild('ChildValues',{ static: false }) childReference: ChildComponent;

 ngAfterViewInit() {
  this.values = this.childReference.this.responseValues;
  console.log(this.values);
  mapResponse(this.values);
}

In here `mapResponse(this.values)` method runs before coming data from `this.values` from child component to parent.
getValues($event) {
  this.values = $event;
  console.log(this.values);
  this.apply();
}

这是我的父组件.html文件

<app-child #ChildValues (getEvent)=" getValues($event)" [name]="name"></app-child>

这是我的子组件.html文件

<button (click)="applyResponses()" mat-raised-button>
  Apply
</button>

这是我的子组件.ts文件

  export class ChildComponent implements OnInit {
      responseValues = {
            names: [],ages: []
        };
      @Output() getEvent = new EventEmitter < any > ();
      @input() name: string;
    
      ngOnInit() {
        this.getNames();
        this.getAges();
        console.log(this.name);
      }
    
     getNames() {
       this.apiService.getnames(Id).subscribe((names) => {
         this.responseValues.names = [names[0].name];
        });
     }
    
     getAges() {
       this.apiService.getages(Id).subscribe((ages) => {
         this.responseValues.ages = [ages[0].age];
        });
     }
      applyResponses() {
        this.getEvent.emit(this.responseValues);
        console.log(this.responseValues);
      }
    }

如何在加载父页面时从子组件获取数据到父组件?

解决方法

为什么不使用child的ngOnInit定义一个新的发射器?

@Output()dataReceived= new EventEmitter < any > ();

ngOnInit()
{
   forkJoin(this.getNames(),this.getAges()).subscribe(([names,ages]:[any[],any[]])=>{
       this.dataReceived.emit({names:names,ages:ages})
   })
}

还有你的父母吗?

<app-child (dataReceived)="storeData($event)"></app-child>
storeData(data:any)
{
    console.log(data.names,data.ages)
}

更新是有关评论中问题的答案,请记住,您不确定是否可以获取数据。为了检查它,我们将“模拟”服务器的缓慢响应。从“ rxjs / operators”导入延迟的原因

import {delay} from 'rxjs/operators'

并通过以下方式更改订阅

this.apiService.getages(Id).pipe(
  delay(10000))
  .subscribe((ages) => {
     this.responseValues.ages = [ages[0].age];
    });

如果您在10秒钟之前单击按钮,则没有数据

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...