Angular中多次触发事件报错:Cannot read properties of undefined (reading 'emit')
问题原因与解决方法
原因
在setInterval中使用普通function作为回调时,this的指向会变成全局的window对象(浏览器环境下),而非Angular组件的实例。这导致回调里的this.incNum和this.numEmitter均为undefined,从而触发Cannot read properties of undefined (reading 'emit')错误。
解决方法
方法1:使用箭头函数
箭头函数不会创建独立的this上下文,它会继承外层作用域的this(即组件实例),直接替换回调即可:
onStart() { this.timer = window.setInterval(() => { this.incNum++; this.numEmitter.emit(this.incNum); }, 1000); }
方法2:提前保存组件实例的this
在setInterval执行前,把组件的this存入变量,回调中通过该变量访问组件属性:
onStart() { const component = this; this.timer = window.setInterval(function () { component.incNum++; component.numEmitter.emit(component.incNum); }, 1000); }
方法3:用bind()绑定this
通过bind()方法将回调函数的this强制绑定为组件实例:
onStart() { this.timer = window.setInterval(function () { this.incNum++; this.numEmitter.emit(this.incNum); }.bind(this), 1000); }
内容的提问来源于stack exchange,提问作者Shubham Maheshwari
相关产品推荐
相关产品推荐

