Search code examples
angularionic-framework

Problem with storage ionic and angular, return undefined data used service


Use this service but return undefined data.

  // Function for get a element to the store
  public async get(name: string): Promise<any> {
    await this._storage?.get(name);
  }

Solution

  • Have you created the _storage var with storage.create(), where storage:Storage?

    storage.create() return a Promise, so before call get or set you have to wait that your storage is created/loaded.

    import { Storage } from '@ionic/storage-angular';
    
    export class DBService {
        private _storage: Storage = null;
        constructor(private storage: Storage) {}
        
        async init() {
            this._storage = await this.storage.create();
        }
    
        async get(key: string) {
            if(!this._storage)
                await this.init() ;
            return await this._storage?.get(key) ;
        }
        async set(key: string, data: any) {
            if(!this._storage)
                await this.init() ;
            return await this._storage?.set(key, data) ;
        }
    }