Currently, I am utilizing the Ionic Storage framework to persist data for long durations. My objective is to retrieve data upon navigating to the Statistics page. However, I encountered an issue where the instantiation of the storage class is not recognized when I call the service methods within the ngOnInit of the statistics page. Strangely enough, the methods work as intended when placed within the ionViewWillEnter() function. Both ngOnInit and ionViewWillEnter are marked as async, yet the error persists for ngOnInit. While I could resort to using the ionViewWillEnter workaround which seems to achieve a similar outcome in my scenario, I am intrigued by the underlying reason for these errors...
Here is the TypeScript code for the statistics page :
import { StatsService } from './../service/stats.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-statistics',
templateUrl: './statistics.page.html',
styleUrls: ['./statistics.page.scss'],
})
export class StatisticsPage implements OnInit {
testsAmount: any = 0;
constructor(public statsService: StatsService) {}
addJohn(){
this.statsService.set("1", "john");
}
removeAll(){
this.statsService.clearAll();
}
async getJohn(){
console.log(await this.statsService.get("1"));
}
async ngOnInit() {
await this.statsService.set("testSetngOnInit", "blabla");
console.log("testSet initialized from the ngOnInit");
console.log(await this.statsService.get("testSetngOnInit"));
}
async ionViewWillEnter(){
await this.statsService.set("testSetionViewWillEnter", "blabla");
console.log("testSet initialized from the ionViewWillEnter");
console.log(await this.statsService.get("testSetionViewWillEnter"));
}
}
Here is the TypeScript code for the Service :
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
@Injectable({
providedIn: 'root'
})
export class StatsService {
// private _storage: Storage | null = null;
private _storage: Storage;
constructor(public storage: Storage) {
this.init();
}
async init() {
// If using, define drivers here: await this.storage.defineDriver(/*...*/);
await this.storage.defineDriver(CordovaSQLiteDriver);
const storage = await this.storage.create();
this._storage = storage;
}
async keyExistence(key: string){
if(await this.get(key) == null){
return false;
}
else{
return true;
}
}
// Create and expose methods that users of this service can
// call, for example:
async set(key: string, value: any) {
await this._storage?.set(key, value);
}
async clearAll() {
await this._storage.clear();
}
async get(key: string) {
return await this._storage.get(key);
}
}
The following output is displayed in the console : https://i.sstatic.net/jD4D7.png
Here is my IndexDB data : https://i.sstatic.net/eUSzN.png
Thank you in advance!