ionic-team / ionic-storage

Ionic Storage module for Ionic apps
MIT License
437 stars 99 forks source link

Method get is not working #313

Open tlloliveira opened 1 year ago

tlloliveira commented 1 year ago

Hello.

I'm using "@ionic/storage-angular": "^4.0.0" on the project. But, the method get return undefined.

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

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
    this.init();
  }

  async init() {
    // If using, define drivers here: await this.storage.defineDriver(/*...*/);
    const storage = await this.storage.create();
    this._storage = storage;
  }

  // Create and expose methods that users of this service can
  // call, for example:
  public set(key: string, value: any) {
    this._storage?.set(key, value);
  }

  public async get(key: string): Promise<any> {
    console.log(key);

    const data = await this._storage?.get(key);
    console.log(data);
    return data;
  }
}

The console shows: login storage.service.ts:31 undefined

theosnel commented 11 months ago

Is your strorage created yet? That is an async function that takes some time. This doesn't seem like a bug to me, just the way it works.

I had some issues with it, because I used the storage indirecty in my auth-guard (via my auth-service), which is needed almost immediately. I solved it by initializing the storage-service in a provider:

In app.module.ts:

import { APP_INITIALIZER } from '@angular/core';
export function appInitializer(storageService: StorageService) {
    return () => storageService.init();
}

Add this to the providers:

    {
      provide: APP_INITIALIZER,
      useFactory: appInitializer,
      multi: true,
      deps: [StorageService]
    }

You don't need to call this.init() in your storage constructor anymore.

I'm not sure if this is the best solution, but at least the entire app waits until the storage is created.

rtpHarry commented 11 months ago

I think you're encountering this: https://github.com/ionic-team/ionic-storage/issues/229

theosnel commented 11 months ago

yes, that looks like the same issue. Totally missed that, thank you.