In this section, we will explore various methods to store data locally in an Ionic application. Local data storage is crucial for creating apps that can function offline and provide a seamless user experience. We will cover the following topics:

  1. Introduction to Local Storage
  2. Using Local Storage in Ionic
  3. Using SQLite for Local Storage
  4. Practical Examples
  5. Exercises

  1. Introduction to Local Storage

Local storage allows you to store data on the user's device. This data persists even after the app is closed and reopened. There are several methods to achieve local storage in Ionic:

  • Local Storage API: A simple key-value storage system.
  • SQLite: A more robust, SQL-based storage system.
  • Ionic Storage: A unified API for various storage engines.

  1. Using Local Storage in Ionic

Local Storage API

The Local Storage API is a simple way to store key-value pairs in the browser. It is easy to use but has limitations in terms of storage capacity and data structure.

Example

// Storing data
localStorage.setItem('username', 'JohnDoe');

// Retrieving data
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

// Removing data
localStorage.removeItem('username');

Ionic Storage

Ionic Storage is a powerful storage solution that provides a simple API for various storage engines, including IndexedDB, SQLite, and WebSQL.

Installation

First, install the Ionic Storage package and the SQLite plugin:

npm install @ionic/storage-angular
npm install cordova-sqlite-storage

Configuration

Next, configure Ionic Storage in your app.module.ts:

import { IonicStorageModule } from '@ionic/storage-angular';

@NgModule({
  imports: [
    IonicStorageModule.forRoot()
  ],
  // other configurations
})
export class AppModule {}

Usage

Now you can use Ionic Storage in your services or components:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private storage: Storage) {
    this.init();
  }

  async init() {
    await this.storage.create();
  }

  // Storing data
  async setUsername(username: string) {
    await this.storage.set('username', username);
  }

  // Retrieving data
  async getUsername() {
    return await this.storage.get('username');
  }

  // Removing data
  async removeUsername() {
    await this.storage.remove('username');
  }
}

  1. Using SQLite for Local Storage

SQLite is a powerful, SQL-based storage solution that is ideal for complex data structures and large datasets.

Installation

Install the SQLite plugin:

ionic cordova plugin add cordova-sqlite-storage
npm install @ionic-native/sqlite

Configuration

Add SQLite to your app.module.ts:

import { SQLite } from '@ionic-native/sqlite/ngx';

@NgModule({
  providers: [
    SQLite
  ],
  // other configurations
})
export class AppModule {}

Usage

Create a service to handle SQLite operations:

import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';

@Injectable({
  providedIn: 'root'
})
export class DatabaseService {
  private dbInstance: SQLiteObject;

  constructor(private sqlite: SQLite) {
    this.init();
  }

  async init() {
    try {
      this.dbInstance = await this.sqlite.create({
        name: 'mydatabase.db',
        location: 'default'
      });
      await this.createTables();
    } catch (error) {
      console.error('Unable to open database', error);
    }
  }

  async createTables() {
    try {
      await this.dbInstance.executeSql(`
        CREATE TABLE IF NOT EXISTS users (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          username TEXT
        );
      `, []);
    } catch (error) {
      console.error('Unable to create tables', error);
    }
  }

  async addUser(username: string) {
    try {
      await this.dbInstance.executeSql(`
        INSERT INTO users (username) VALUES (?);
      `, [username]);
    } catch (error) {
      console.error('Unable to add user', error);
    }
  }

  async getUsers() {
    try {
      const res = await this.dbInstance.executeSql(`
        SELECT * FROM users;
      `, []);
      let users = [];
      for (let i = 0; i < res.rows.length; i++) {
        users.push(res.rows.item(i));
      }
      return users;
    } catch (error) {
      console.error('Unable to get users', error);
    }
  }
}

  1. Practical Examples

Example 1: Using Ionic Storage

import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';

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

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.loadUsername();
  }

  async loadUsername() {
    this.username = await this.dataService.getUsername();
  }

  async saveUsername() {
    await this.dataService.setUsername(this.username);
  }

  async clearUsername() {
    await this.dataService.removeUsername();
    this.username = '';
  }
}

Example 2: Using SQLite

import { Component, OnInit } from '@angular/core';
import { DatabaseService } from '../services/database.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.page.html',
  styleUrls: ['./users.page.scss'],
})
export class UsersPage implements OnInit {
  users: any[] = [];
  newUsername: string;

  constructor(private dbService: DatabaseService) {}

  ngOnInit() {
    this.loadUsers();
  }

  async loadUsers() {
    this.users = await this.dbService.getUsers();
  }

  async addUser() {
    await this.dbService.addUser(this.newUsername);
    this.newUsername = '';
    this.loadUsers();
  }
}

  1. Exercises

Exercise 1: Using Ionic Storage

  1. Create a new Ionic page called Settings.
  2. Add a form to the Settings page to save user preferences (e.g., theme, notifications).
  3. Use Ionic Storage to save and retrieve these preferences.

Exercise 2: Using SQLite

  1. Create a new Ionic page called Notes.
  2. Add a form to the Notes page to add new notes.
  3. Use SQLite to save and retrieve notes.

Solutions

Solution 1: Using Ionic Storage

// settings.page.ts
import { Component, OnInit } from '@angular/core';
import { Storage } from '@ionic/storage-angular';

@Component({
  selector: 'app-settings',
  templateUrl: './settings.page.html',
  styleUrls: ['./settings.page.scss'],
})
export class SettingsPage implements OnInit {
  theme: string;
  notifications: boolean;

  constructor(private storage: Storage) {}

  ngOnInit() {
    this.loadPreferences();
  }

  async loadPreferences() {
    this.theme = await this.storage.get('theme');
    this.notifications = await this.storage.get('notifications');
  }

  async savePreferences() {
    await this.storage.set('theme', this.theme);
    await this.storage.set('notifications', this.notifications);
  }
}

Solution 2: Using SQLite

// notes.page.ts
import { Component, OnInit } from '@angular/core';
import { DatabaseService } from '../services/database.service';

@Component({
  selector: 'app-notes',
  templateUrl: './notes.page.html',
  styleUrls: ['./notes.page.scss'],
})
export class NotesPage implements OnInit {
  notes: any[] = [];
  newNote: string;

  constructor(private dbService: DatabaseService) {}

  ngOnInit() {
    this.loadNotes();
  }

  async loadNotes() {
    this.notes = await this.dbService.getNotes();
  }

  async addNote() {
    await this.dbService.addNote(this.newNote);
    this.newNote = '';
    this.loadNotes();
  }
}

Conclusion

In this section, we covered various methods to store data locally in an Ionic application, including the Local Storage API, Ionic Storage, and SQLite. We provided practical examples and exercises to help you understand and implement local storage in your apps. In the next section, we will explore using Ionic Storage in more detail.

© Copyright 2024. All rights reserved