我一直在尝试制作一个简单的表格,然后将数据插入其中以了解 Ionic 2 框架的工作原理,但我被问题困住了,无法解决它。我尝试了不同的谷歌解决方案,但没有一个奏效。
注意:我是 Ionic 2 的新手,最初是原生的 Android 开发人员。
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
/**
* Generated class for the AddProductsPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-add-products',
templateUrl: 'add-products.html',
})
export class AddProductsPage {
productName: string;
sqlstorage: SQLite;
items: Array<Object>;
db: SQLiteObject;
mesg: string;
constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) {
this.platform.ready().then(() => {
this.sqlstorage = new SQLite();
this.sqlstorage.create({ name: "test.db", location: "default" }).then(() => {
console.log("SuccessDB");
this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
// this.createTables();
}, (err) => {
console.log("DB !!! ", err);
});
});
}
presentToast() {
let toast = this.toastCtrl.create({
message: this.mesg,
duration: 3000,
position: 'top'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
addProduct() {
this.addItem("insert into product (productName) values(?)", this.productName);
this.findAll();
}
public createTables() {
this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
}
public addItem(q: string, param: string) {
this.db.executeSql(q, param).then((data) => {
console.log("Success");
}, (e) => {
console.log("Error : " + JSON.stringify(e.err));
});
}
public findAll() {
this.db.executeSql("SELECT * FROM items", []).then((data) => {
this.items = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
this.items.push(data.rows.item(i));
this.mesg = data.rows.item(i);
console.log(this.mesg);
}
}
}, (e) => {
this.mesg = "Errot: " + JSON.stringify(e);
console.log("Errot: " + JSON.stringify(e));
});
this.presentToast();
}
}
这是来自设备的错误
OPEN database: test.db SQLitePlugin.js:175
new transaction is waiting for open operation SQLitePlugin.js:106
OPEN database: test.db - OK
ERROR
Error {rejection: TypeError, promise: t, zone: r, task: t}
message: "Uncaught (in promise): TypeError: Cannot call method 'executeSql' of undefined↵TypeError: Cannot call method 'executeSql' of undefined↵ at AddProductsPage.createTables (file:///android_asset/www/build/main.js:58248:17)↵ at file:///android_asset/www/build/main.js:58226:23↵ at t.invoke (file:///android_asset/www/build/polyfills.js:3:9283)↵ at Object.inner.inner.fork.onInvoke (file:///android_asset/www/build/main.js:4649:37)↵ at t.invoke (file:///android_asset/www/build/polyfills.js:3:9223)↵ at r.run (file:///android_asset/www/build/polyfills.js:3:4452)↵ at file:///android_asset/www/build/polyfills.js:3:14076↵ at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9967)↵ at Object.inner.inner.fork.onInvokeTask (file:///android_asset/www/build/main.js:4640:37)↵ at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9888)"
promise: t
rejection: TypeError
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
task: t
zone: r
__proto__: d
main.js:1584
defaultErrorLogger main.js:1584
ErrorHandler.handleError main.js:1644
IonicErrorHandler.handleError main.js:117966
onError.subscribe.next main.js:5278
schedulerFn main.js:4351
SafeSubscriber.__tryOrUnsub main.js:15685
SafeSubscriber.next main.js:15632
Subscriber._next main.js:15572
Subscriber.next main.js:15536
Subject.next main.js:18926
EventEmitter.emit main.js:4337
NgZone.triggerError main.js:4709
inner.inner.fork.onHandleError main.js:4670
t.handleError polyfills.js:3
r.runGuarded polyfills.js:3
(anonymous function) polyfills.js:3
n.microtaskDrainDone polyfills.js:3
o
编辑:
带有不执行插入查询的错误的代码。(addProduct 方法在单击触发器时执行。
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
/**
* Generated class for the AddProductsPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-add-products',
templateUrl: 'add-products.html',
})
export class AddProductsPage {
productName: string;
sqlstorage: SQLite;
items: Array<Object>;
db: SQLiteObject;
mesg: string;
constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) {
this.platform.ready().then(() => {
this.sqlstorage = new SQLite();
this.sqlstorage.create({
name: 'data.db',
location: 'default'
}).then((db: SQLiteObject) => {
this.db = db;
console.log("Opened");
db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
db.executeSql("insert into product (ProductID,ProductName) values(3,'jhkj')", []);
}).catch(e => {
console.log(e);
});
});
}
presentToast() {
let toast = this.toastCtrl.create({
message: this.mesg,
duration: 3000,
position: 'top'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
addProduct() {
// this.sqlstorage = new SQLite();
// this.sqlstorage.create({
// name: 'data.db',
// location: 'default'
// }).then((db: SQLiteObject) => {
// console.log("Opened");
return new Promise((resolve, reject) => {
this.db.executeSql("insert into product (productName) values(?)", this.productName).then((data) => {
resolve(data);
console.log("resolve");
}, (error) => {
reject(error);
console.log("reject");
});
});
// this.addItem("insert into product (productName) values(?)", this.productName, db);
// this.findAll(db);
// }).catch(e => {
// console.log(e);
// });
}
public createTables() {
this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
}
public addItem(q: string, param: string, db: SQLiteObject) {
db.executeSql(q, param).then((data) => {
console.log("Success");
}, (e) => {
console.log("Error : " + JSON.stringify(e.err));
});
}
public findAll(db: SQLiteObject) {
db.executeSql("SELECT * FROM product", []).then((data) => {
this.items = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
this.items.push(data.rows.item(i));
this.mesg = data.rows.item(i);
console.log(this.mesg);
}
}
}, (e) => {
this.mesg = "Errot: " + JSON.stringify(e);
console.log("Errot: " + JSON.stringify(e));
});
this.presentToast();
}
}
发生此错误是因为您尝试使用未初始化的 SQLiteObject db。当你使用 SQLite 的创建方法时,它会返回一个 SQLiteObject,你可以用它来执行你的 SQL 查询。这是一个例子——
this.sqlite.create({
name: 'data.db',
location: 'default'
}).then((db: SQLiteObject) => {
console.log("Opened");
db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
}).catch(e => {
console.log(e);
});