Hello everyone,
I am currently trying to understand how to store the data of my app (e.g user data) with a database. I need this data to be persistent because its going to be used later on.
I have seen that there is this SQLite plugin (https://github.com/litehelpers/Cordova-sqlite-storage), however I think I don't understand some basics about storing data in a database in Ionic v2.
I already started to write a little provider with functions that should create a database and a table for me. Where should I call this function for the first time? Is it meant to be inside the constructor of my provider like in this example?
constructor(public http: Http, private platform: Platform, private sqlite: SQLite) {
this.platform.ready()
.then( () => {
this.createDB()
.then( () => {
this.initTables();
})
})
}
createDB(): Promise<any>{
return new Promise( (resolve, reject) => {
try {
this.database.create({name: 'data.db', location: 'default'})
.then( (db: SQLiteObject) => {
this.database = db;
})
} catch (err) {
reject( {err: err} );
}
})
}
initTables(){
this.platform.ready().then( () => {
this.database.transaction( (tx: any) => {
tx.executeSql('CREATE TABLE IF NOT EXISTS User(id INT NOT NULL, name VARCHAR(40) NOT NULL)');
})
.then( () => { console.log('Created User table') })
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
});
}
Also what I would like to know is if this example code is in general the correct way of doing it? If it is not, could you maybe provide me a little example on how to do it properly?
Thanks in advance