Angular4中如何将对象列表的值推入数组?代码实现咨询
解决Angular4中异步数据处理的问题
嘿,我看到你遇到的问题了——核心原因是Observable的订阅是异步操作,你现在的代码把forEach写在了subscribe外面,这时候数据还没从服务端返回呢,this.EmployeeData要么是undefined要么是空数组,自然没法把数据push到resultArray里。
下面给你两种正确的实现方式,先讲清楚步骤:
第一步:提前初始化数组
先在组件类里把用到的数组初始化,避免出现Cannot read property 'forEach' of undefined的错误:
export class YourComponent { EmployeeData: any[] = []; resultArray: any[] = []; constructor(private userService: employeeviewservices) {} }
第二步:把数据处理逻辑移到subscribe回调内部
只有当服务返回数据后,subscribe的回调函数才会执行,这时候this.EmployeeData才有真实数据,再去处理就没问题了。
方式一:用forEach循环push(和你原来的逻辑一致)
ngOnInit() { // 推荐把初始化逻辑放在ngOnInit,而不是构造函数里,这是Angular的最佳实践 this.userService.employeeView().subscribe(data => { this.EmployeeData = data; // 现在数据已经拿到了,放心循环处理 this.EmployeeData.forEach(i => { this.resultArray.push({ id: i.id, name: i.name }); }); }); }
方式二:用map更简洁(推荐)
如果只是把原数组转换成新结构,用Array.map()会更简洁,直接生成新数组赋值给resultArray:
ngOnInit() { this.userService.employeeView().subscribe(data => { this.EmployeeData = data; this.resultArray = this.EmployeeData.map(i => ({ id: i.id, name: i.name })); }); }
为什么原代码不行?
再给你理清楚代码执行顺序:
- 调用
this.userService.employeeView(),发送HTTP请求(异步操作) - 立即执行后面的
this.EmployeeData.forEach(...),这时候请求还没完成,this.EmployeeData还是初始的空数组/undefined - 等请求完成、数据返回后,才会执行subscribe里的
this.EmployeeData=data,但这时候forEach已经执行过了,所以完全没效果
另外提醒下:Angular4里如果用的是HttpClient(代替旧的Http),要确保已经在模块里导入HttpClientModule哦。
内容的提问来源于stack exchange,提问作者Manik
相关产品推荐
相关产品推荐

