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
相关产品推荐
相关产品推荐

