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

Error: A cyclic dependency cannot be instantiated. The ApplicationRef ("[ERROR ->]") is occurring in the NgModule AppModule within ./AppModule@-1:-1

I recently implemented the following code in my app.module.ts file: providers: [ AppConfigService, { provide: APP_INITIALIZER, useFactory: (config: AppConfigService) => () => config.getAppConfig(), ...

ngx-slick-carousel: a carousel that loops infinitely and adjusts responsively

I have implemented ngx-slick-carousel to showcase YouTube videos in my project. However, I am facing two main issues. Firstly, the carousel is not infinite, and when the last video is reached, there appears to be white spaces before it loops back to the fi ...

Exploring the Combination of PyQt4 and SQLAlchemy for Effortless Data Management in QTableView

As I dive into learning Qt for Python, I came across an interesting post on Stack Overflow discussing an issue with QTableView not populating when changing databases. This got me thinking - is there a way to utilize SQLAlchemy sessions instead of constantl ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

Polling database from various browser tabs

Working on a .NET/angular application that regularly checks the SQL Server database for updates, with the user able to customize the polling interval starting from 10 seconds (as per business requirements). The issue arises when each new tab opened by a ...

Creating dynamic lists in Angular with ngFor: A step-by-step guide

I am currently working on an Angular 7 application and have a component that retrieves a JSON array. @Component({ selector: 'app-indices-get', templateUrl: './indices-get.component.html', styleUrls: ['./indices-get.component ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...

What is the best way to assign values to mat-select in Angular using the component class?

I am currently delving into the world of Angular and experimenting with my own Angular code. HTML Component <mat-form-field class="select-country-component"> <mat-label>Select Country</mat-label> <mat ...

Using node-fetch version 3.0.0 with jest results in a SyntaxError stating that import statements cannot be used outside a module

Recently, I've been updating my API to utilize node-fetch 3.0.0. One major change highlighted in their documentation is that node-fetch is now a pure ESM module. Click here for more information on the changes This update caused some of my unit tests ...

Angular2 - leveraging root-relative imports

Having trouble with imports in angular2/typescript? Want to use paths relative to the project root like 'app/components/calendar', but currently stuck using something like this: //app/views/order/order-view.ts import {Calendar} from '../../ ...

Communication between parent and child components in Angular 2 using objects

When you create a parent component and a child component, if you assign a primitive value (string, number, boolean) to the child component, you need to create an @Input and an @Output with EventEmitter to enable two-way communication. This process seems st ...

Error: The package name "@angular/compiler" is not valid in Npm

After successfully installing Ionic2 for a new project, I proceeded to set up a continuous integration build. However, running npm install on the build server resulted in failure with the following error: npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:&bso ...

Issue with exporting member in VS Code but not in console

I currently have a NestJS project (project A) with one module that utilizes the @nestjs/typeorm and typeorm packages. In my other NestJS project (project B), I plan to use this module. However, there is a potential issue. Project B contains entities that ...

One way to consolidate multiple components in a single location without altering user-input data

I currently have 3 separate components, namely PersonalInfoComponent, EducationalInfoComponent, and ExperienceComponent. These components are all being displayed within the ResumeComponent. The issue I am facing is that when a user enters information in t ...

Typescript Support in Goland IDE for HTML Documents

I'm currently utilizing Go for my programming tasks, and I prefer the Goland IDE developed by Jetbrains. Is there a way for me to incorporate typescript into my .html template files that contain a mix of HTML, CSS, and JS? Your assistance is much ap ...

Sharing Information Across Angular Routes

I've been encountering a slight issue when working with routes in Angular 4. Whenever I attempt to pass data from one component to another using navigate('root', data), all I end up receiving is [object Object],[object Object],[object Object ...