Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method get is not working #313

Open
tlloliveira opened this issue Nov 27, 2023 · 3 comments
Open

Method get is not working #313

tlloliveira opened this issue Nov 27, 2023 · 3 comments

Comments

@tlloliveira
Copy link

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
Copy link

theosnel commented Dec 6, 2023

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
Copy link
Contributor

rtpHarry commented Dec 8, 2023

I think you're encountering this: #229

@theosnel
Copy link

theosnel commented Dec 8, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants