semmelbroesl
semmelbroesl

Reputation: 43

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 contacts and save them to your sqlite database.

I got this:

import { Storage ] from '@ionic/storage';
    @component({
        selector: 'page-home'
        templateUrl: 'home.html'
});

export class HomePage {

  posts: any;
  persons: any;

constructor(public navCtrl: NavController, public http: Http, public storage: Storage) {

  this.http.get('https://jsonplaceholder.typicode.com/users').map(res=> res.json()).subscribe(data => {
  this.posts = data;
 });

}

//here i would like to recieve the data from the tapped Item

  setData(){
    console.log();
        this.storage.set('myData', this.posts);
        console.log(this.posts);
  };


  getData(){
     this.storage.get('myData').then((data) => {
       if (data !=null){
         console.log(data);
       }
    })
  };
}

Here is the View: When i click / tap the save-button i would like to store the values in my sqlite-database and display them in my "local contacts".

<ion-content>
        <ion-list>
            <ion-item *ngFor="let post of posts">
                <ion-list>
                    <ul><h1>{{post.name}}</h1></ul>
                    <ul><p>{{post.username}}, {{post.email}}</p></ul>
                    <ul><p>phone: {{post.phone}}</p></ul>
                    <button ion-button (click)="setData()">Set Data</button>
                </ion-list>
            </ion-item>
        </ion-list>
    </ion-content>

Maybe someone faced similar problems and can help me with this. Thanks :)

Upvotes: 2

Views: 1338

Answers (1)

maninak
maninak

Reputation: 2726

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: [...],
})
export class AppModule { }

2. Inject Storage into your component

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  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 */})
});

Upvotes: 2

Related Questions