angular - 如何将来自 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);
}
}
如何在父页面加载时从子组件获取数据到父组件?
解决方案
为什么不在孩子的 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 秒前单击按钮,则您没有数据
推荐阅读
- firebase - Go 是否支持实时 Firebase 事件?
- python - libdouble-conversion.so.1:无法打开共享对象文件:没有这样的文件或目录
- python - 如何在 True 时替换?
- ssl - 使用 IP 时 SSL 异常名称与证书的通用名称不匹配
- python - 如何抓取包含字符串字符的属性(python,beautifulsoup)
- highcharts - Highcharts Highmaps 如何从谷歌电子表格导入数据
- reactjs - 对 Redux 不变性的工作方式感到困惑
- sass - 如何在 scss 的函数或 mixin 中传递自定义属性?
- virtual-machine - 尝试连接到 pfsence Web 界面
- c++ - 如何创建一个 C++ 宏来定义使用调用另一个函数的参数列表的函数?