首页 > 解决方案 > 如何将来自 Observable 的异步数据返回从子组件传递到 Angular 中的父组件

问题描述

我正在尝试将异步数据从子组件传递到父组件。但是在这里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);
      }
    }

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

标签: angulartypescriptangular-componentsviewchildasyncdata

解决方案


为什么不在孩子的 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 秒前单击按钮,则您没有数据


推荐阅读