Angular 4 TypeScript报错:Cannot read property 'list' of undefined
解决"Cannot read property 'list' of undefined"问题
你遇到的这个错误和数组初始化无关,核心问题是**forEach回调函数里的this指向不对**。
问题原因
在普通的function()回调中,this的指向会脱离你的类实例(默认指向全局对象,严格模式下是undefined),所以当你在回调里访问this.list时,自然找不到这个属性,就会抛出"Cannot read property 'list' of undefined"的错误。
解决方案
这里有几种常用的修复方式,按推荐程度排序:
1. 使用箭头函数(ES6+推荐方案)
箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的类实例)。修改后的代码如下:
list: Array<any> = []; // 注意:如果第一个forEach只是用来重置list为空,其实可以直接删掉,因为你已经初始化过了 this.data.forEach((element) => { this.list.push({ 'name': this.url }); });
2. 提前保存this到变量
在forEach外部把类实例的this存到一个变量(比如that),然后在回调里用这个变量访问属性:
list: Array<any> = []; const that = this; this.data.forEach(function(element) { // that.list = []; that.list.push({ 'name': that.url }); });
3. 使用bind()绑定this
给forEach的回调函数显式绑定类实例的this:
list: Array<any> = []; this.data.forEach(function(element) { // this.list = []; this.list.push({ 'name': this.url }); }.bind(this));
额外提示
你原来的代码里有两个独立的forEach调用,第一个里面把list重置为空数组,如果这不是你预期的逻辑(比如你只是想初始化后添加元素),可以直接删掉第一个forEach,避免不必要的数组重置操作。
内容的提问来源于stack exchange,提问作者yer
相关产品推荐
相关产品推荐

