在PouchDB回调中调用服务出现TypeError:无法设置undefined的itemsList
解决Angular/Ionic中PouchDB回调里
Cannot set property 'itemsList' of undefined的问题 嘿,这个问题我太熟了——核心就是回调函数里的this指向不对!你在db.allDocs里用了普通的function作为回调,这时候this已经不再指向你的ContactListsPage组件实例了,自然找不到itemsList和commonServiceProvider这些组件属性。
给你两种简单靠谱的解决办法:
方法1:改用箭头函数(推荐)
箭头函数不会创建自己的this上下文,它会直接继承外层(也就是组件类)的this,完美适配这种场景:
修改后的ionViewDidLoad代码:
ionViewDidLoad() { this.setupDB(); //DB Setup // Function to check if doc exists in DB or not this.db.allDocs({ include_docs: true, attachments: true }, (err, response) => { // 这里改成箭头函数 if (!err) { //if DB don't have any doc, call the contact service to fetch data if (response.total_rows == 0) { this.commonServiceProvider.fetchContacts() .subscribe((data: any) => { if (data.responseCode === 0) { this.itemsList = data.contacts; // Insert service data in DB this.db.bulkDocs(data.contacts, (err, result) => { if (err) { console.log(err); } }); } }, err => { console.log(err); }); } else { this.itemsList = response.rows; } } else { console.log(err); } }); }
方法2:提前保存组件的this到变量
如果不想用箭头函数,也可以在回调外面把组件的this存到一个变量里(比如self),然后在回调里用self代替this:
ionViewDidLoad() { this.setupDB(); //DB Setup const self = this; // 保存组件的this到变量 // Function to check if doc exists in DB or not this.db.allDocs({ include_docs: true, attachments: true }, function (err, response) { if (!err) { //if DB don't have any doc, call the contact service to fetch data if (response.total_rows == 0) { self.commonServiceProvider.fetchContacts() // 用self代替this .subscribe((data: any) => { if (data.responseCode === 0) { self.itemsList = data.contacts; // 这里也是self // Insert service data in DB self.db.bulkDocs(data.contacts, (err, result) => { if (err) { console.log(err); } }); } }, err => { console.log(err); }); } else { self.itemsList = response.rows; // 这里同样用self } } else { console.log(err); } }); }
两种方法都能解决问题,个人更推荐第一种箭头函数的写法,更简洁符合现代TypeScript/Angular的编码习惯。
内容的提问来源于stack exchange,提问作者Priyank
相关产品推荐
相关产品推荐

