Skip to content Skip to sidebar Skip to footer

How Can I Pass Data Into My Sqlite-database

Hello there :) I am pretty new to programming and I recently started an IONIC App. However I got stuck. I want to do something like a phone book where you can get random JSON cont

Solution 1:

The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from'@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
exportclassAppModule { }

2. Inject Storage into your component

import { Component } from'@angular/core';
import { Storage } from'@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
exportclassHomePage {
  constructor(public storage: Storage) {}
}

3. Storing data in SQLite

Whenever you access storage, make sure to always wrap your code in the following:

storage.ready().then(() => { /* code here safely */});

3.1 Saving a key-value pair

storage.ready().then(() => {
    storage.set('some key', 'some value');
});

3.2 Retrieving a value

storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});

3.3 Deleting a key-value pair

storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});

Post a Comment for "How Can I Pass Data Into My Sqlite-database"