gpt4 book ai didi

javascript - TypeScript(JavaScript) 中的项目范围

转载 作者:行者123 更新时间:2023-11-28 18:36:00 25 4
gpt4 key购买 nike

我想在ionic2中使用sqlite数据库。

我可以通过以下代码成功连接到数据库并检索项目数据。但我无法插入 this.items 数组。

错误说:

undefined is not an object(evaluating 'this.items')

有谁知道问题出在哪里吗?我猜它的范围是可变的,但我不确定。

import {Page, Platform} from 'ionic-angular';
declare var sqlitePlugin:any;
declare var plugins:any;

@Page({
templateUrl: 'build/pages/getting-started/getting-started.html'
})
export class GettingStartedPage {
items: Array<{title: string}>;
constructor(platform: Platform) {
platform.ready().then(()=>{
this.getData();
});
}

getData(){
sqlitePlugin.openDatabase({name: 'encrypted.db', key: 'Password', location: 'default'}, function(db) {
db.transaction(function(tx) {
var query: string = "SELECT * FROM items";
this.items = []; <-- error happens at this row.
tx.executeSql(query, [], function(tx, resultSet) {
//alert("name: " + resultSet.rows.item(0).name);
this.items.push({
title: resultSet.rows.item(0).name
});
}, function(error) {
alert('SELECT error: ' + error.message);
console.log('SELECT error: ' + error.message);
});
}, function(error) {
alert('transaction error: ' + error.message);
console.log('transaction error: ' + error.message);
}, function() {
console.log('transaction ok');
});
}, function(error){
alert('error' + error.message);
});
}
}

最佳答案

使用() =>代替function ()

arrow functions this 一直指向类而不是当前函数。

import {Page, Platform} from 'ionic-angular';
declare var sqlitePlugin:any;
declare var plugins:any;

@Page({
templateUrl: 'build/pages/getting-started/getting-started.html'
})
export class GettingStartedPage {
items: Array<{title: string}>;
constructor(platform: Platform) {
platform.ready().then(()=>{
this.getData();
});
}

getData(){
sqlitePlugin.openDatabase({name: 'encrypted.db', key: 'Password', location: 'default'}, (db) => {
db.transaction((tx) => {
var query: string = "SELECT * FROM items";
this.items = []; <-- error happens at this row.
tx.executeSql(query, [], (tx, resultSet) => {
//alert("name: " + resultSet.rows.item(0).name);
this.items.push({
title: resultSet.rows.item(0).name
});
}, (error) => {
alert('SELECT error: ' + error.message);
console.log('SELECT error: ' + error.message);
});
}, (error) => {
alert('transaction error: ' + error.message);
console.log('transaction error: ' + error.message);
}, () => {
console.log('transaction ok');
});
}, (error) =>{
alert('error' + error.message);
});
}
}

关于javascript - TypeScript(JavaScript) 中的项目范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37066891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com