Angular 5中调用ionViewDidLoad内方法报objectNotify未定义错误求助
解决Angular 5/Ionic中
Cannot read property 'objectNotify' of undefined的问题 嘿,我之前也踩过这个坑!这个错误本质是notifyMethod里的this没有正确指向你的NotificationsPage组件实例,所以找不到你声明的objectNotify对象。咱们来一步步搞定它:
常见原因&对应解决方案
1. 用箭头函数定义方法(最省心的方案)
箭头函数不会创建自己的this上下文,它会自动继承外层(也就是你的组件实例)的this。把notifyMethod改成箭头函数形式就行:
export class NotificationsPage { public objectNotify = {}; constructor(public navCtrl: NavController, public navParams: NavParams, public db: AngularFireDatabase) { } ionViewDidLoad() { this.notifyMethod(); } // 改成箭头函数 notifyMethod = () => { this.objectNotify["name"] = "John"; console.log(this.objectNotify); } }
2. 在构造函数里手动绑定this
如果你更习惯用普通函数定义方法,可以在构造函数里把this绑定到notifyMethod上,确保不管在哪里调用它,this都指向组件实例:
export class NotificationsPage { public objectNotify = {}; constructor(public navCtrl: NavController, public navParams: NavParams, public db: AngularFireDatabase) { // 手动绑定this到方法 this.notifyMethod = this.notifyMethod.bind(this); } ionViewDidLoad() { this.notifyMethod(); } notifyMethod() { this.objectNotify["name"] = "John"; console.log(this.objectNotify); } }
3. 检查模板中的方法绑定(如果有)
如果你是在模板里通过事件触发notifyMethod,一定要记得加括号!比如:
<!-- 正确写法 --> <button (click)="notifyMethod()">触发通知</button> <!-- 错误写法(会导致this丢失) --> <button (click)="notifyMethod">触发通知</button>
不加括号的话,方法会被当作普通函数调用,严格模式下this会变成undefined。
4. 异步回调里用箭头函数
如果你的notifyMethod里有异步操作(比如调用AngularFireDatabase的接口),一定要在回调里用箭头函数,不然this会指向回调函数本身,而不是组件:
notifyMethod() { // 用箭头函数作为subscribe的回调 this.db.list('some-path').valueChanges().subscribe(data => { this.objectNotify["name"] = "John"; console.log(this.objectNotify); }); }
你可以根据自己的实际代码情况选一个方案试试,基本都能解决这个问题~
内容的提问来源于stack exchange,提问作者Darshan theerth
相关产品推荐
相关产品推荐

