What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database.

Here's my current code snippet:

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);
       }
    })
  };
}

On the View side: When clicking/tapping the save button, I aim to store the values in my sqlite-database and display them as "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>

If anyone has tackled similar challenges and can offer guidance, I'd greatly appreciate it. Thanks a lot! :)

Answer №1

If you're looking for a reliable way to manage persistent storage in Ionic, consider leveraging ionic-storage.

Developed and maintained by the dedicated team at Ionic, Ionic Storage serves as a robust package designed to streamline development by abstracting the complexities of individual browsers or platforms while seamlessly utilizing the most optimal storage solution available.


1. Setting Up Dependencies

To utilize SQLite in your project, ensure you install the necessary dependencies for both Angular and Cordova:

npm install @ionic/storage --save

Furthermore, run:

cordova plugin add cordova-sqlite-storage --save

Next, update the NgModule declaration in src/app/app.module.ts to include 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. Accessing Storage in 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. Data Storage Using SQLite

Remember to wrap all storage-related code within the following block when accessing storage:

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

3.1 Saving Key-Value Pairs

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

3.2 Retrieving Values

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

3.3 Deleting Key-Value Pairs

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to delete previously entered characters in the "confirm password" field after editing the password

Is there a way to automatically remove characters in the confirm password field if characters are removed from the password field? Currently, when characters are entered into the password field, characters can also be entered into the confirm password fiel ...

Is there a way for me to loop through an object without prior knowledge of its keys?

Upon receiving data from the server, it looks something like this: { "2021-10-13": { "1. open": "141.2350", "2. high": "141.4000", "3. low": "139.2000", "4. close& ...

What steps can be taken to resolve the "value" parameter exceeding the range error in Protractor?

Currently, I am utilizing Angular 7 in combination with Protractor for end-to-end automated test cases. Additionally, I have incorporated BrowserStack for testing my project across multiple browsers. Within my project, there is an image upload feature for ...

incapable of altering the function of individual parts within ionic 3

I am currently working on creating a list of people for users to connect with. When a user clicks on the connect button, it should send a connection request to the chosen person. However, I am facing an issue where clicking on the connect button changes th ...

What steps can be taken to ensure that only users with "admin" status have the ability to edit certain data within a Firebase document?

Within my Angular application, I have implemented Firestore for storing user profiles. Currently, the structure looks like this: /profiles/{uid}/: { displayName: "Luigi",//--> Only editable by Luigi email: "<a href="/cdn-cgi/l/email-protecti ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

How can we postpone the initiation of Angular tests?

I am currently facing a challenge with integrating a proprietary 3rd party library into my Angular project. This library asynchronously injects elements into the window object that are crucial for many of my components to function properly. However, before ...

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Issue: 10 iterations of $digest() have been exceeded

I'm currently facing an issue with my code that involves repeating and displaying the items in a cart. <div ng-repeat="retailer in cart.getOrderedByRetailer()" > <ion-item> {{retailer.retailer_name}} </ion-item> ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Having trouble achieving the desired effect with inline block

I'm having some trouble creating a simple store page. One of the products is supposed to look like this: However, it's currently showing up like this: I've been attempting to use inline block so that I can have the negotiate button and pro ...

The element is inferred to have an 'any' type due to the inability to use a 'string' type expression to index the 'Palette' type

Encountering an issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'. No index signature with a parameter of type 'string' was found on type &ap ...

Unable to populate data in dropdown using Angular framework?

My datatable displays elements along with an edit button. At the top of the page, there is also an add button. The purpose of the add button is to add elements to the list, while the edit button allows for editing the data in a particular row. When the u ...

Disabling `no-dupe-keys` in ESLint does not seem to be effective

Currently, I am working on a project where I have incorporated Typescript and ESLint. However, I have encountered an issue with the error message stating: An object literal cannot have multiple properties with the same name. I am looking to disable this s ...

What is the best way to add a value to a nested JSON array in Angular 5?

Need help transferring nested JSON data format from Web API to Angular5 {"contractId":1, "contractName":"Temp", "contractServiceList":[ {"id":1, "serviceId":{"serviceId":1,"serviceName":"Emergency Room"}, "providerTier":"Tier 1", "coi ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...