Saving Application Data
We’ve dealt with saving the photo files using native storage, but we also need to store data in our application as well - just like we did for our Quicklists application. We might have a photo saved on the users device, but we still need our application to remember the path to that photo, and that is what we will be storing using Ionic’s Storage API.
There isn’t going to be anything new here - we will be doing just what we did with the Quicklists application, but this will actually be a little easier since we only need to store one type of data.
Adding Ionic Storage
Install the following packages:
npm install @ionic/storage-angular
npm install localforage-cordovasqlitedriver
Add the following import to your root NgModule:
IonicStorageModule.forRoot({
driverOrder: [
// eslint-disable-next-line no-underscore-dangle
CordovaSQLiteDriver._driver,
Drivers.IndexedDB,
Drivers.LocalStorage,
],
}),
NOTE: You will also need the following imports at the top of the file containing your root module:
import { Drivers } from '@ionic/storage';
import { IonicStorageModule } from '@ionic/storage-angular';
import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
Creating the Storage Service
Create a file at
src/app/shared/data-access/storage.service.ts
and add the following:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import { from, Observable } from 'rxjs';
import { map, shareReplay, switchMap, take, tap } from 'rxjs/operators';
import { Photo } from '../interfaces/photo';
@Injectable({
providedIn: 'root',
})
export class StorageService {
#hasLoaded = false;
storage$ = from(this.ionicStorage.create()).pipe(shareReplay(1));
load$: Observable<Photo[]> = this.storage$.pipe(
switchMap((storage) => from(storage.get('photos'))),
map((photos) => photos ?? []),
tap(() => (this.#hasLoaded = true)),
shareReplay(1)
);
constructor(private ionicStorage: Storage) {}
save(photos: Photo[]) {
if (this.#hasLoaded) {
this.storage$.pipe(take(1)).subscribe((storage) => {
storage.set('photos', photos);
});
}
}
}