如何解决如何在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秒钟之前单击按钮,则没有数据
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。