我应该在我的应用程序中的何处创建SQLite db实例?

我应该在我的应用程序中的何处创建SQLite db实例?,sqlite,ionic-framework,ionic2,Sqlite,Ionic Framework,Ionic2,我正在创建一个Ionic 2移动应用程序,它将使用SQLite数据库来存储数据。我知道我必须使用下面的代码访问数据库: this.sqlite.create({ name: 'data.db', location: 'default' }) .then((db: SQLiteObject) => { db.executeSql('create table danceMoves(name VARCHAR(32))', {}) .then(() =>

我正在创建一个Ionic 2移动应用程序,它将使用SQLite数据库来存储数据。我知道我必须使用下面的代码访问数据库:

this.sqlite.create({
    name: 'data.db',
    location: 'default'
})
.then((db: SQLiteObject) => {
    db.executeSql('create table danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
.catch(e => console.log(e));

考虑到我的应用程序中会有几个页面访问db,我的问题是什么时候应该使用create方法来获取db对象实例:每次我需要执行一个命令,还是应该执行一次并将db实例放入全局变量中?

您可以创建一个单例提供程序,作为sqlite db的接口

@Injectable()
export class StorageService {

 constructor(private sqlite: SQLite){
  this.sqlite.create({
    name: 'data.db',
    location: 'default'
})
.then((db: SQLiteObject) => {
    db.executeSql('create table danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
.catch(e => console.log(e));
}


//other db access functions like insert, get, delete etc.
}
在app.module.ts中,将其设置为提供者,并在需要时注入