Using Firebase to Persist Data Tutorial | Complete Guide [STEP-IN]
Last updated on 18th Aug 2022, Blog, Tutorials
Ionic Database
Ionic Angular SQLite info tutorial throughout this gradual guide, you’ll determine a way to produce SQLite CRUD operation within the Ionic Angular app with the SQLite packages facilitated. Ideally, SQLite is a powerful info completely accustomed to producing info systems in smaller devices which permit the United States to perform SQL queries and build an easy app with CRUD operations. Generically, during this fast guide, we’ll demonstrate a way to produce associate degree SQLite info, produce a table and insert into device info, add or insert knowledge into the table. Fetch, get or browse knowledge from the table, delete a row from the table, and update the row from the table in ionic sqlite offline mobile app.
Ionic half-dozen SQLite Offline CRUD Mobile App Example:
Step 1: tack together Ionic setting
Step 2: Update Routes
Step 3: Install SQLite Plugin
Step 4: Update App Module category
Step 6: produce SQLite CRUD Service
Step 7: Implement produce and Delete
Step 8: Get knowledge assortment and show List
Step 9: Implement Update or Edit
Step 10: check Ionic Crud App
Configure Ionic setting Ionic interface may be a must-have tool; so, begin with putting in it. Run the command to launch
the installation process: npm install -g @ionic/cli Next, install the new blank
ionic angular app: ionic begin ionic-sqlite-crud blank –type=angular
Head over to project folder:
cd ionic-sqlite-crud Next, generate ionic pages or elements with the assistance of the steered command. guarantee to delete the house page as a result of we have a tendency to not want that. ng generate page create ng generate page edit Remove kind Errors You have to get rid of strict kind errors confirm to line “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.
Update Routes:
Next, head over to the app routing file; add the id property within the edit route significantly set the product as a default route.
- import { NgModule } from ‘@angular/core’;
- import { PreloadAllModules, RouterModule, Routes } from
- ‘@angular/router’;
- const routes: Routes = [
- {
- path: ”,
- redirectTo: ‘create’,
- pathMatch: ‘full’
- },
- {
- path: ‘create’,
- loadChildren: () => import(‘./create/create.module’).then( m =>
- m.CreatePageModule)
- },
- {
- path: ‘edit/:id’,
- loadChildren: () => import(‘./edit/edit.module’).then( m =>
- m.EditPageModule)
- },
- ];
- @NgModule({
- imports: [
- RouterModule.forRoot(routes, { preloadingStrategy:
- PreloadAllModules })
- ],
- exports: [RouterModule]
- })
- export class AppRoutingModule { }
Update app-routing.module.ts file:
npm install @ionic-native/sqlite
ionic cordova plugin add cordova-sqlite-storage
npm i @ionic-native/core
Install SQLite Plugin:
This is the foremost representative step; as per the instruction, we want to put in the SQLite and Ionic native core plugins. Open the terminal, kind command and so execute.
npm install @ionic-native/sqlite
ionic cordova plugin add cordova-sqlite-storage
npm i @ionic-native/core
Update App Module class:
Further, we want to import the SQLite plugin into the app module category, and it offers United States access to its ways and functions to use throughout the app.
- import { NgModule } from ‘@angular/core’;
- import { BrowserModule } from ‘@angular/platform-browser’;
- import { RouteReuseStrategy } from ‘@angular/router’;
- import { IonicModule, IonicRouteStrategy } from ‘@ionic/angular’;
- import { AppComponent } from ‘./app.component#39;;
- import { AppRoutingModule } from ‘./app-routing.module#39;;
- // plugins
- import { SQLite } from ‘@ionic-native/sqlite/ngx’;
- @NgModule({
- declarations: [AppComponent],
- entryComponents: [],
- imports: [BrowserModule, IonicModule.forRoot(),
- AppRoutingModule],
- providers: [
- SQLite,
- {
- provide: RouteReuseStrategy,
- useless: IonicRouteStrategy
- }
- ],
- bootstrap: [AppComponent],
- })
- export class AppModule {}
Create SQLite CRUD Service:
Angular service is best for code manageableness and reusability paradigm. Consequently, generate the service for ionic offline crud mobile app mistreatment the subsequent command. ng g service crud In the next step, we’ve got to form and add, read, update and delete ways. Most significantly, we’ve got to invoke the SQLite info association within the Ionic app from the ionic, angular service file. The sqlite offers a methodology that takes info name and placement and initializes the SQLite info association. Above command manifests crud.service.ts file, opens it and updates the steered code inside the file.
- import { Injectable } from ‘@angular/core’;
- import { Platform } from ‘@ionic/angular’;
- import { SQLite, SQLiteObject } from ‘@ionic-native/sqlite/ngx’;
- @Injectable({
- providedIn: ‘root n#39;
- })
- export class CrudService {
- private dbInstance: SQLiteObject;
- readonly db_name: string = “remotestack.”;
- readonly db_table: string = “userTable”;
- USERS: Array <any> ;
- constructor(
- private platform: Platform,
- private sqlite: SQLite
- ) {
- this.databaseConn();
- }
- // Create SQLite database
- databaseConn() {
- this.platform.ready().then(() => {
- this.sqlite.create({
- name: this.db_name,
- location: ‘default’
- }).then((sqLite: SQLiteObject) => {
- this.dbInstance = sqLite;
- sqLite.executeSql(`
- CREATE TABLE IF NOT EXISTS ${this.db_table} (
- user_id INTEGER PRIMARY KEY,
- name varchar(255),
- email varchar(255)
- )`, [])
- .then((res) => {
- // alert(JSON.stringify(res));
- })
- .catch((error) => alert(JSON.stringify(error)));
- })
- .catch((error) => alert(JSON.stringify(error)));
- });
- }
- // Crud
- public addItem(n, e) {
- // validation
- if (!n.length || !e.length) {
- alert(‘Provide both email & name’);
- return;
- }
- this.dbInstance.executeSql( `
- INSERT INTO ${this.db_table} (name, email) VALUES (‘${n}’,
- ‘${e}’)`, [])
- .then(() => {
- alert(“Success “);
- this.getAllUsers();
- }, (e) => {
- alert(JSON.stringify(e.err));
- });
- }
- getAllUsers() {
- return this.dbInstance.executeSql(`SELECT * FROM
- ${this.db_table}`, []).then((res) => {
- this.USERS = [];
- if (res.rows.length > 0) {
- for (var i = 0; i < res.rows.length; i++) {
- this.USERS.push(res.rows.item(i));
- }
- return this.USERS;
- }
- },(e) => {
- alert(JSON.stringify(e));
- });
- }
- // Get user
- getUser(id): Promise <any> {
- return this.dbInstance.executeSql(`SELECT * FROM
- ${this.db_table} WHERE user_id = ?`, [id])
- .then((res) => {
- return {
- user_id: res.rows.item(0).user_id,
- name: res.rows.item(0).name,
- email: res.rows.item(0).email
- }
- });
- }
- // Update
- updateUser(id, name, email) {
- let data = [name, email];
- return this.dbInstance.executeSql(`UPDATE ${this.db_table}
- SET name = ?, email = ? WHERE user_id = ${id}`, data)
- }
- // Delete
- deleteUser(user) {
- this.dbInstance.executeSql(`
- DELETE FROM ${this.db_table} WHERE user_id = ${user}`, []) .
- then(() => {
- alert(“User deleted!”);
- this.getAllUsers();
- })
- .catch(e => {
- alert(JSON.stringify(e))
- });
- }
- }
We have to perform multiple tasks mistreatment service file, 1st import Platform, SQLite and SQLiteObject modules. These are essential for making and fixing the SQLite info association once the platform is prepared. To handle CRUD operations we have a tendency to mistreat SQLite, which enables writing MYSql queries with executeSql() methodology. Moreover, we have a tendency to create SQLite info association, create info, create and insert tables into the info. Also, addItem(), getAllUsers(), getUser(), updateUser() and deleteUser() for handling CRUD events.
Implement create and Delete:
In this step, you we’ll learn to implement a way to produce and show list features in ionic page mistreatment of SQLite. In this step, we’ll add a basic kind to let users enter knowledge like name and email mistreatment ngModel. Use CrudService by mercantilism and adding into the creator methodology, access ways making user, attractive users list from the SQLite info and deleting user objects from the SQLite sound unit.
Add code in create.page.ts file:
- import { Component, OnInit } from ‘@angular/core’;
- import { CrudService } from ‘../crud.service#39;;
- @Component({
- selector: ‘app-create#39;,
- templateUrl: ‘./create.page.html ‘,
- styleUrls: [‘./create.page.scss ‘],
- })
- export class CreatePage implements OnInit {
- nameVal: string = “”;
- emailVal: string = “”;
- constructor(
- private crud: CrudService
- ) {
- this.crud.databaseConn();
- }
- ngOnInit() { }
- ionViewDidEnter() {
- this.crud.getAllUsers()
- }
- createUser(){
- this.crud.addItem(this.nameVal, this.emailVal);
- }
- remove(user) {
- this.crud.deleteUser(user);
- }
- }
To show the info assortment, use the ngFor directive to repeat over the USERS assortment and show it into the ionic item UI part.
Add code in create.page.html file:
- <ion-header >
- <in-toolbar >
- <in-titles gt;Ionic SQLite Storage Example </ion-title >
- </ion-toolbar >
- </ion-header >
- <ion-content >
- <!– Create –>
- <ion-item >
- <ion-label position=”floating “>Name </ion-label >
- <ion-input [(ngModel)]=”nameVal”></ion-input >
- </ion-item >
- <ion-item >
- <ion-label position=”floating “>Email</ion-label >
- <ion-input [(ngModel)]=”emailVal”></ion-input >
- </ion-item >
- <ion-button color=”success” expand=”unlock”
- (click)=”createUser()”>
- Add User
- </ion-button >
- <!– Read –>
- <ion-item *ngFor=”let user of crud.USERS “>
- <ion-label >
- <h2><strong>{{ user.name }}</strong></h2>
- <p>{{ user.email }}</p>
- </ion-label >
- <div class=”item-note” item-end>
- <ion-icon color=”primary ” name=”create” style=”zoom:1.3″
- [routerLink]=”[‘/edit/’, user.user_id]”></ion-icon >
- <ion-icon color=”danger” name=”trash” style=”zoom:1.3″
- (click)=”remove(user.user_id)”></ion-icon >
- </div>
- </ion-item >
- </ion-content >
Implement Update or Edit
Lastly, we’ll implement the edit or update feature thus confirm to form the shape and insert the web log values by mistreating the angular service.
- import { Component, OnInit } from ‘@angular/core’;
- import { CrudService } from ‘../crud.service#39;;
- import { ActivatedRoute, Router } from “@angular/router”;
- @Component({
- selector: ‘app-edit#39;,
- templateUrl: ‘./edit.page.html ‘,
- styleUrls: [‘./edit.page.css#39;],
- })
- export class EditPage implements OnInit {
- id: any;
- nameVal: string = “”;
- emailVal: string = “”;
- constructor(
- private router: Router
- private activatedRoute: ActivatedRoute,
- private crud: CrudService
- ) {
- this.id = this.activatedRoute.snapshot.paramMap.get(‘id&t#39;);
- this.crud.getUser(this.id).then((res) => {
- this.nameVal = res[‘name’];
- this.emailVal Valores[’email#39;];
- })
- }
- ngOnInit() { }
- onUpdate() {
- this.crud.updateUser(this.id, this.nameVal,
- this.emailVal).then(() => {
- this.router.navigate([‘/create n#39;]);
- })
- }
- }
Additionally, we have a tendency to used the ActivatedRoute api to urge the userid from the uniform resource locator, and it’s being passed to the getUser()methodology. this can be obtaining the only user object from the SQLite info, likewise mistreatment the updateUser() methodology to update the user knowledge.
Update edit.page.ts file:
- <ion-header >
- <in-toolbar >
- <ion-buttons slot=”start”>
- <ion-back-button ></ion-back-button >
- </ion-buttons gt;
- <in-title >Edit</ion-title >
- </ion-toolbar >
- </ion-header >
- <ion-content >
- <ion-item >
- <ion-label position=”floating “>Name </ion-label >
- <ion-input [(ngModel)]=”nameVal”></ion-input >
- </ion-item >
- <ion-item >
- <ion-label position=”floating “>Email</ion-label >
- <ion-input [(ngModel)]=”emailVal”></ion-input >
- </ion-item >
- <ion-button color=”dark” expand=”unlock” (click)=”onUpdate()”> Update
- </ion-button >
- </ion-content >
Test Ionic Crud App:
In the ultimate step, you would like to follow the suggested directions to start out the ionic crud example app:
Include the platform:
- # iOS
- ionic cordova platform add ios
- # Android
- ionic cordova platform add android
- Thereafter, create the runnable build:
- # iOS
- ionic cordova build ios
- # Android
- ionic cordova build android
- Ultimately, run the app on the device:
- # iOS
- ionic cordova run ios -l
- # Android
- ionic cordova run android -l
Conclusion:
So this was it; the Ionic SQLite CRUD mobile app tutorial is completed for now; During this example, we have a tendency to delineate a way to produce associate degree Ionic CRUD mobile app mistreatment SQLite info plugins. Implementing the SQLite info within the Ionic app offers quick access to SQLite info ways that we are able to use to store and manage the info for building offline mobile apps. Not simply that, we have a tendency to conjointly understand the crud app building method gradually. That consists of making an associate degree app, putting in plugins,fixing plugins to access info ways, making the angular service for reusable code, and implementing the crud operations in ionic pages.
Are you looking training with Right Jobs?
Contact Us- Windows Azure Interview Questions and Answers
- Salesforce Architecture Tutorial
- Wrapper Class in Salesforce Tutorial
- salesforce lightning
Related Articles
Popular Courses
- VM Ware Training
11025 Learners
- Microsoft Dynamics Training
12022 Learners
- Siebel Training
11141 Learners
- What is Dimension Reduction? | Know the techniques
- Difference between Data Lake vs Data Warehouse: A Complete Guide For Beginners with Best Practices
- What is Dimension Reduction? | Know the techniques
- What does the Yield keyword do and How to use Yield in python ? [ OverView ]
- Agile Sprint Planning | Everything You Need to Know