Ionic2中从回调函数调用set方法报错,求解决方案
解决回调函数中
this.set()报错的问题 这问题我之前开发时也踩过坑!核心原因是你写的success回调是普通函数,它改变了this的指向——这里的this不再指向你的组件实例,自然找不到set方法,所以才会报错。
给你三种靠谱的解决方案,选你习惯的用就行:
方案1:使用箭头函数(推荐)
箭头函数不会绑定自己的this,会继承外层上下文的this,这样回调里的this就和组件实例保持一致了:
smsRead(){ var options = { delimiter : "OTP is", length : 6, origin : "ENTIND" }; // 把普通函数改成箭头函数 var success = (otp) => { this.set(otp); localStorage.setItem('otp', otp) ; OTPAutoVerification.stopOTPListener(); } var failure = function () { OTPAutoVerification.stopOTPListener(); // 你的failure逻辑 } // ... 其他代码 }
方案2:提前保存组件的this到变量
在smsRead函数开头先把组件的this存到一个变量里(比如that),然后在回调里用这个变量代替this:
smsRead(){ const that = this; // 先保存组件的this var options = { delimiter : "OTP is", length : 6, origin : "ENTIND" }; var success = function (otp) { that.set(otp); // 用that调用set方法 localStorage.setItem('otp', otp) ; OTPAutoVerification.stopOTPListener(); } var failure = function () { OTPAutoVerification.stopOTPListener(); // 你的failure逻辑 } // ... 其他代码 }
方案3:用bind绑定this
给success函数手动绑定组件的this,确保回调执行时this指向正确:
smsRead(){ var options = { delimiter : "OTP is", length : 6, origin : "ENTIND" }; var success = function (otp) { this.set(otp); localStorage.setItem('otp', otp) ; OTPAutoVerification.stopOTPListener(); }.bind(this); // 绑定组件的this var failure = function () { OTPAutoVerification.stopOTPListener(); // 你的failure逻辑 } // ... 其他代码 }
简单总结下:普通函数作为回调时,this的指向会被调用它的环境改变,而箭头函数、保存this、bind这三种方法,都是为了让回调里的this始终指向你的组件实例,这样就能正常调用set方法啦。
内容的提问来源于stack exchange,提问作者Vinod Vishwakarma
相关产品推荐
相关产品推荐

