Skip to content

Method get is not working #313

Open
Open

Description

@tlloliveira

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

Activity

  1. theosnel commented on Dec 6, 2023

    @theosnel

    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.

  2. rtpHarry commented on Dec 8, 2023

    @rtpHarry
    Contributor

    I think you're encountering this: #229

  3. theosnel commented on Dec 8, 2023

    @theosnel

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions