Ionic/Angular Storage Tutorial and Example

Ionic/Angular Storage Tutorial and Example

In this article, you will learn how to easily store and persist key-value pairs and JSON objects by making advantage of Ionic 5 and Angular's local and native storage. Ionic Storage is able to encapsulate all of the many mechanisms that are currently available for storing data. These include native Cordova SQLite as well as browser storage APIs like as IndexedDB, WebSQL, and localStorage.

Depending on your use case or the underlying platform, the method that is going to be the most comfortable for you will be chosen automatically. One example of this would be for native apps that are operating on mobile devices. For the purpose of storage, SQLite will be utilised; however, localStorage or IndexedDB will be used in situations when there is no native storage available, such as when Progressive Web Apps are operating on a browser platform.

What is Ionic?

Ionic is not a newcomer to the market for the building of mobile apps. Ionic was first released in 2013 as an open-source software development kit (SDK) for hybrid mobile applications. As of this writing, more than 5 million apps have been produced using Ionic. It is well-known for being able to provide platform-specific UI elements by means of a library of native components for both iOS and Android. Ionic is essentially a npm module, and therefore must have Node.js installed in order for it to function properly as a component of a big JavaScript ecosystem.

Front-end technology and WebView. Ionic is an application development framework that makes use of front-end technologies such as HTML, CSS, JavaScript, and Angular. Ionic is a framework that makes it easier to build cross-platform mobile applications using web technologies and a single codebase. In a nutshell, it grants web developers the ability to design web pages that may be executed within the browser instance of a device known as WebView. The WebView component is essentially an application component that renders web pages and displays them as if they were a native application. WebView may be distributed as a plugin.

Built on top of Apache Cordova and Angular. The initial versions of Ionic were built on top of Angular, which is a well-known front-end framework that is typically employed for the construction of dynamic web pages and progressive web applications, or PWAs for short. Ionic has the ability to construct completely functional mobile applications by utilising Angular's CLI (Command-Line Interface) and component libraries.

Apache Cordova plugins are the foundation of yet another component of Ionic that is responsible for accessing native capabilities. Cordova is a framework for constructing mobile applications utilising web technologies. Instead of relying on APIs that are platform-specific, Cordova uses its own APIs. Because it relies on WebView, Ionic does not, by default, have access to the APIs of the device on which it is running. Cordova gives developers access to a smartphone's camera, gyroscope, and other sensors by providing the appropriate application programming interfaces (APIs) in the form of plugins. These collections of application programming interfaces are also known as the Cordova Bridge. Ionic applications have access to native application programming interfaces (APIs) thanks to Apache Cordova, which acts as a bridge between the webview and the operating system of the device.

Ionic Indigenous. When developing an application, your goal should be to incorporate all of the necessary features as much as possible. Ionic Native was developed specifically for this reason. It is a collection of Cordova plugins that has been developed to support integration and standard APIs. Ionic Native is offered in two different editions: the free Community Edition and the premium Enterprise Edition. The Enterprise Edition is an extended version that has been curated by the Ionic team.

Executing the SQLite Cordova Plugin Installation Procedure

Cordova's cordova-plugin-nativestorage plugin allows faster and larger data storage. It works well as Native storage for Windows, Android, and iOS devices. Before you can use SQLite as a storage option for native apps, you will first need to install the Cordova plugin for SQLite by using the following command:. Afterwards, you will be able to utilise SQLite as a storage option.

ionic cordova plugin add cordova-plugin-nativestorage
Bash

In order to use the Storage functionality, run the script that will install the Ionic Native plugin.

npm install @ionic-native/native-storage
Bash

Next, you will need to add it to the list of imports in the src/app/app.module.ts file, just like you would with any other module:

import { IonicStorageModule } from '@ionic/storage';
....  
@NgModule({
  ......
  imports: [      
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  .....
})
export class AppModule {}

You may begin use the Storge API in any component now by just injecting it through the function Object() { [native code] } of the component you wish to utilise it in. Therefore, let's develop a comprehensive demonstration that demonstrates how you may use the Storage API within an application built with Ionic 5 or Angular (either native app or progressive web app).

Storage in Ionic Cordova SQLite

We utilise Ionic's storage module in conjunction with Cordova's cordova-sqlite-storage plugin to save the data in key/value pairs and JSON format respectively. Cordova's sqlite storage plugin is used to save the data.

SQLite is utilised in Ionic 4 for the development of native applications that run on mobile devices. Data can be stored in Progressive Web Apps using either the browser's built-in localStorage or IndexedDB, both of which function normally within the browser. However, the way that works best for you will rely on the requirements that your platform has.

Create an Ionic 5/Angular Application

Launch your command prompt or terminal and type in the following command to initiate the creation of an Ionic 5 project:

ionic start ionic-storage-example blank --type=angular

This will result in the creation of a new project based on the blank template, which will just contain a home page by default (this is sufficient for our example demo).

The next step is to open your preferred code editor and navigate within the directory that contains your project. I'll be using VSCode.

First, make sure you install everything correctly by following the directions in the "Getting Started" section up above.

Next, navigate to the directory src/pages/home/home.ts and open it. Import the Storage class, and then inject it.

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

@Component({
 selector: 'app-home',
 templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage {

  constructor(public storage: Storage) {}
}

Let's say for the sake of argument that you want some app settings, like the theme colour, to be saved. Using the APIs provided by the Storage class, such as the get() and set() methods, we are able to accomplish this as follows:

   set(settingName: any, value: any){ // set item
    return this.storage.set(`setting: ${ settingName }`, value);
  }
   async get(settingName: any){ // fetch item
    return await this.storage.get(`setting: ${ settingName }`);
  }
   async remove(settingName: any){ // remove item
    return await this.storage.remove(`setting: ${ settingName }`);
  }
   clear() { // Clear all
    this.storage.clear().then(() => {
      // Cleared!
    });
  }

It is important to take note that these methods all return Promises. Additionally, for the sake of this straightforward demonstration, we added these methods to the component; however, typically, it is best practise to house logic of this kind within Angular services.

implementing the User Interface

Now, let's create some buttons so that these methods can be triggered:

To add the following code, open the src/pages/home/home.html file and select it.

<ion-content class="ion-padding">
  <ion-button (click)="set('color', 'blue')"> Set Blue Color </ion-button>
  <ion-button (click)="remove('color')"> Remove Color </ion-button>
</ion-content>

Simple values, such as characters and numbers, as well as more complicated JSON objects can be used for values.

Conclusion

This concludes our walkthrough of the Ionic 5/Angular Storage class, which demonstrated how to store key-value pairs and JSON objects respectively. You might want to think about utilising Ionic Native SQLite or PouchDB for more complex CRUD operations. Subscribe us on YouTube for more.


Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !