You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
    }));
  });
}

为什么原代码不行?

再给你理清楚代码执行顺序:

  1. 调用this.userService.employeeView(),发送HTTP请求(异步操作)
  2. 立即执行后面的this.EmployeeData.forEach(...),这时候请求还没完成,this.EmployeeData还是初始的空数组/undefined
  3. 等请求完成、数据返回后,才会执行subscribe里的this.EmployeeData=data,但这时候forEach已经执行过了,所以完全没效果

另外提醒下:Angular4里如果用的是HttpClient(代替旧的Http),要确保已经在模块里导入HttpClientModule哦。

内容的提问来源于stack exchange,提问作者Manik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:46:37