我想将MySQL服务器数据库同步到ionic 2中的本地sqlite数据库,以便使用户能够离线存储信息,然后在在线时调用/发送更改。
我已经看到了几种使其在 android 中工作的方法,但我在 ionic 2 中没有找到太多关于它的信息。
我们假设您已经安装了 Node.js并且能够在 Node.js命令行 (Windows) 或终端 (OS X/Linux) 中运行npm
。要确保所有内容都是最新的,请在终端或节点命令行中键入此命令。
npm install -g ionic cordova
要添加 Ionic 3 Native SQLite 和 Toast 插件,只需键入以下命令。
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
ionic cordova plugin add cordova-plugin-x-toast
npm install --save @ionic-native/toast
现在,打开并编辑src/app/app.module.ts
然后添加此导入。
import { SQLite } from '@ionic-native/sqlite';
import { Toast } from '@ionic-native/toast';
将SQLite
和Toast
添加到@NgModule
提供程序,因此它将如下所示。
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
SQLite,
Toast
]
使用Ionic 3,Angular 4和SQLite实现CRUD移动应用程序首先创建费用列表。为此,请打开并编辑默认src/pages/home/home.ts
然后添加此导入。
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { AddDataPage } from '../add-data/add-data';
import { EditDataPage } from '../edit-data/edit-data';
两次导入"添加"和"编辑数据"需要新页面来添加和编辑稍后添加的数据。现在,在构造函数变量上注入SQLite
。
constructor(public navCtrl: NavController,
private sqlite: SQLite) {}
在构造函数之前为费用数组、总收入、总费用和余额添加此变量。
expenses: any = [];
totalIncome = 0;
totalExpense = 0;
balance = 0;
在构造函数下方添加此函数以获得完整的 CRUD。
ionViewDidLoad() {
this.getData();
}
ionViewWillEnter() {
this.getData();
}
getData() {
this.sqlite.create({
name: 'ionicdb.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('CREATE TABLE IF NOT EXISTS expense(rowid INTEGER PRIMARY KEY, date TEXT, type TEXT, description TEXT, amount INT)', {})
.then(res => console.log('Executed SQL'))
.catch(e => console.log(e));
db.executeSql('SELECT * FROM expense ORDER BY rowid DESC', {})
.then(res => {
this.expenses = [];
for(var i=0; i<res.rows.length; i++) {
this.expenses.push({rowid:res.rows.item(i).rowid,date:res.rows.item(i).date,type:res.rows.item(i).type,description:res.rows.item(i).description,amount:res.rows.item(i).amount})
}
})
.catch(e => console.log(e));
db.executeSql('SELECT SUM(amount) AS totalIncome FROM expense WHERE type="Income"', {})
.then(res => {
if(res.rows.length>0) {
this.totalIncome = parseInt(res.rows.item(0).totalIncome);
this.balance = this.totalIncome-this.totalExpense;
}
})
.catch(e => console.log(e));
db.executeSql('SELECT SUM(amount) AS totalExpense FROM expense WHERE type="Expense"', {})
.then(res => {
if(res.rows.length>0) {
this.totalExpense = parseInt(res.rows.item(0).totalExpense);
this.balance = this.totalIncome-this.totalExpense;
}
})
}).catch(e => console.log(e));
}
addData() {
this.navCtrl.push(AddDataPage);
}
editData(rowid) {
this.navCtrl.push(EditDataPage, {
rowid:rowid
});
}
deleteData(rowid) {
this.sqlite.create({
name: 'ionicdb.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('DELETE FROM expense WHERE rowid=?', [rowid])
.then(res => {
console.log(res);
this.getData();
})
.catch(e => console.log(e));
}).catch(e => console.log(e));
}
接下来,打开并编辑src/pages/home/home.html
然后用它替换所有代码。
<ion-header>
<ion-navbar>
<ion-title>
My Expense
</ion-title>
<ion-buttons end>
<button ion-button icon-only (click)="addData()">
<ion-icon name="add-circle"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Expense List</h2>
<ion-list>
<ion-item-sliding *ngFor="let expense of expenses; let i=index">
<ion-item nopadding>
<p>
<span>{{expense.date}}</span><br>
Type: {{expense.type}}<br>
{{expense.description}}
</p>
<h3 item-end>
Amount: ${{expense.amount}}
</h3>
</ion-item>
<ion-item-options side="right">
<button ion-button color="primary" (click)="editData(expense.rowid)">
<ion-icon name="paper"></ion-icon>
</button>
<button ion-button color="danger" (click)="deleteData(expense.rowid)">
<ion-icon name="trash"></ion-icon>
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-title>Balance: ${{balance}}</ion-title>
</ion-toolbar>
</ion-footer>
键入此命令以创建新页面以添加新数据。
ionic g page AddData
打开并编辑src/pages/add-data/add-data.ts
然后用它替换所有代码。
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Toast } from '@ionic-native/toast';
@IonicPage()
@Component({
selector: 'page-add-data',
templateUrl: 'add-data.html',
})
export class AddDataPage {
data = { date:"", type:"", description:"", amount:0 };
constructor(public navCtrl: NavController,
public navParams: NavParams,
private sqlite: SQLite,
private toast: Toast) {}
saveData() {
this.sqlite.create({
name: 'ionicdb.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('INSERT INTO expense VALUES(NULL,?,?,?,?)',[this.data.date,this.data.type,this.data.description,this.data.amount])
.then(res => {
console.log(res);
this.toast.show('Data saved', '5000', 'center').subscribe(
toast => {
this.navCtrl.popToRoot();
}
);
})
.catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}).catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}
}
接下来,打开并编辑src/pages/add-data/add-data.html
然后用它替换所有代码。
<ion-header>
<ion-navbar>
<ion-title>My Expense</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Add Data</h2>
<form (ngSubmit)="saveData()">
<ion-item>
<ion-label>Date</ion-label>
<ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="data.date" name="date" required=""></ion-datetime>
</ion-item>
<ion-item>
<ion-label>Type</ion-label>
<ion-select [(ngModel)]="data.type" name="type" required="">
<ion-option value="Income">Income</ion-option>
<ion-option value="Expense">Expense</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Description</ion-label>
<ion-input type="text" placeholder="Description" [(ngModel)]="data.description" name="description" required="" ></ion-input>
</ion-item>
<ion-item>
<ion-label>Amount</ion-label>
<ion-input type="number" placeholder="Amount" [(ngModel)]="data.amount" name="amount" required="" ></ion-input>
</ion-item>
<button ion-button type="submit" block>Save Data</button>
</form>
</ion-content>
键入此命令以创建用于编辑数据的新页面。
ionic g page EditData
打开并编辑src/pages/edit-data/edit-data.ts
然后用它替换所有代码。
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Toast } from '@ionic-native/toast';
@IonicPage()
@Component({
selector: 'page-edit-data',
templateUrl: 'edit-data.html',
})
export class EditDataPage {
data = { rowid:0, date:"", type:"", description:"", amount:0 };
constructor(public navCtrl: NavController,
public navParams: NavParams,
private sqlite: SQLite,
private toast: Toast) {
this.getCurrentData(navParams.get("rowid"));
}
getCurrentData(rowid) {
this.sqlite.create({
name: 'ionicdb.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('SELECT * FROM expense WHERE rowid=?', [rowid])
.then(res => {
if(res.rows.length > 0) {
this.data.rowid = res.rows.item(0).rowid;
this.data.date = res.rows.item(0).date;
this.data.type = res.rows.item(0).type;
this.data.description = res.rows.item(0).description;
this.data.amount = res.rows.item(0).amount;
}
})
.catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}).catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}
updateData() {
this.sqlite.create({
name: 'ionicdb.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('UPDATE expense SET date=?,type=?,description=?,amount=? WHERE rowid=?',[this.data.date,this.data.type,this.data.description,this.data.amount,this.data.rowid])
.then(res => {
console.log(res);
this.toast.show('Data updated', '5000', 'center').subscribe(
toast => {
this.navCtrl.popToRoot();
}
);
})
.catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}).catch(e => {
console.log(e);
this.toast.show(e, '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
});
}
}
接下来,打开并编辑src/pages/edit-data/edit-data.html
然后用它替换所有代码。
<ion-header>
<ion-navbar>
<ion-title>My Expense</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Edit Data</h2>
<form (ngSubmit)="updateData()">
<ion-item>
<ion-label>Date</ion-label>
<ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="data.date" name="date" required=""></ion-datetime>
</ion-item>
<ion-item>
<ion-label>Type</ion-label>
<ion-select [(ngModel)]="data.type" name="type" required="">
<ion-option value="Income">Income</ion-option>
<ion-option value="Expense">Expense</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Description</ion-label>
<ion-input type="text" placeholder="Description" [(ngModel)]="data.description" name="description" required="" ></ion-input>
</ion-item>
<ion-item>
<ion-label>Amount</ion-label>
<ion-input type="number" placeholder="Amount" [(ngModel)]="data.amount" name="amount" required="" ></ion-input>
</ion-item>
<ion-input type="hidden" [(ngModel)]="data.rowid" name="rowid"></ion-input>
<button ion-button type="submit" block>Update Data</button>
</form>
</ion-content>
在设备上运行 Ionic 3、Angular 4 和 SQLite 应用程序之前,请先删除并添加平台。
ionic cordova platform rm android
ionic cordova platform rm ios
ionic cordova platform add android
ionic cordova platform add ios
现在,在返回当前文件夹后运行应用程序。
适用于 iOS
ionic cordova run ios
对于Android应该与iOS相同,除了UI行为。可以通过键入此命令来运行。
ionic cordova run android
问候。
-
首先,您需要在应用程序启动时读取所有数据。创建一个服务,返回应用脱机时所需的所有表和记录。让它在后台运行。
-
读取完成后,将其导入本地 SqLite。我更喜欢使用 https://ionicframework.com/docs/native/sqlite-porter/尽管您必须重组返回的 JSON。
-
现在,当应用程序脱机时,无论何时提出请求,都必须从 SqLite 本地读取它。
-
插入、更新或删除数据时,请为每条记录添加一个列(如标志),表明此记录已被修改、添加或删除。
-
当应用程序联机时,读取所有修改的记录并发送回服务器。