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

Angular中无法使用.push操作数组:jsonArr未定义问题求助

解决Angular中Cannot read property 'jsonArr' of undefined的问题

嘿,这个问题我太熟了!核心原因就是你在forEach的回调函数里,this的指向跑偏了,导致找不到服务里的jsonArr属性。咱们来一步步搞定它:

问题出在哪?

你看这段代码:

data[0].companies.forEach(function(cur){
  this.jsonArr.push({ name: cur.name,... });
});

这里用了普通的function作为回调,它会创建自己的作用域,里面的this不再指向你的DataServiceProvider实例,而是变成了window(浏览器环境)或者undefined(严格模式下),自然就找不到jsonArr了。

三种解决方案任你选

1. 用箭头函数(最推荐)

箭头函数不会绑定自己的this,它会直接继承外层作用域的this,这样就能准确访问到服务里的jsonArr:

processProfiles(){
  this.getProfiles().then( data=>{
    data[0].companies.forEach((cur) => {
      this.jsonArr.push({ name: cur.name,... });
    });
  });
}

2. 提前把this存起来

在forEach之前,把当前的this存到一个变量里(比如self或者that),然后在回调里用这个变量代替this:

processProfiles(){
  const self = this;
  this.getProfiles().then( data=>{
    data[0].companies.forEach(function(cur){
      self.jsonArr.push({ name: cur.name,... });
    });
  });
}

3. 用bind绑定this

给普通的回调函数绑定当前的this,强制它指向你的服务实例:

processProfiles(){
  this.getProfiles().then( data=>{
    data[0].companies.forEach(function(cur){
      this.jsonArr.push({ name: cur.name,... });
    }.bind(this));
  });
}

另外提个小建议:如果你的Angular版本比较新,建议把旧的Http模块换成HttpClient,它会自动帮你解析JSON响应,不用再手动调用data.json()啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:35:20