Ionic 3中出现TypeError: Cannot read property 'push' of undefined问题求助
解决TypeError: Cannot read property 'push' of undefined的问题
这个问题我太熟悉啦!核心原因是你在subscribe的成功回调里用了普通的function定义函数,导致this的指向发生了变化——这里的this不再指向你的组件实例,自然就找不到navCtrl,也就会抛出push属性未定义的错误。
下面给你几个可行的解决方案:
方案1:使用箭头函数(推荐)
箭头函数不会改变this的指向,它会继承外层上下文的this,也就是组件实例:
this.http.post('http://localhost:3030/users', userDetails).subscribe( (response) => { this.navCtrl.push(HomePage); }, (response) => { // 处理500错误 } );
方案2:提前保存this到变量
在调用subscribe之前,把组件的this存到一个变量里(比如self或者that),然后在回调里用这个变量:
const self = this; this.http.post('http://localhost:3030/users', userDetails).subscribe( function successCallback(response) { self.navCtrl.push(HomePage); }, function errorCallback(response) { // 处理500错误 } );
方案3:用bind绑定this
给回调函数绑定组件的this,强制它的指向正确:
this.http.post('http://localhost:3030/users', userDetails).subscribe( function successCallback(response) { this.navCtrl.push(HomePage); }.bind(this), function errorCallback(response) { // 处理500错误 }.bind(this) );
其中箭头函数是ES6+的写法,代码更简洁,也是现在最常用的解决这类this指向问题的方式,优先推荐哦!
内容的提问来源于stack exchange,提问作者Chakri
相关产品推荐
相关产品推荐

