Ionic 5 Storage data not persistent between components

Hi All!
In my newly created app I’m accessing storage in multiple places
As suggested I create for that purpose storage service as following:

src/services/storage_service.ts

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() {
    const storage = await this.storage.create();
    this._storage = storage;
  }

  async set(key: string, value: any): Promise<any> {
    return await this._storage?.set(key, value);
  }

  async get(key: string): Promise<any> {
    return await this._storage?.get(key);
  }

  async remove(key: string): Promise<any> {
    return await this._storage?.remove(key);
  }
}

Everything works fine under single component:

    this.localStorage.set('user', '1').then((user) => {
      console.log("Local storege set: ");
      console.log(user);
      this.localStorage.get('user').then((data) => {
        console.log("Local storege get:");
        console.log(data);
        this.navCtrl.navigateRoot('/landing');
      });
    });
  }

but when I’m attempting to retrieve values at next component it returns undefined
Of course on each component I’m including StorageService at providers:

import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';

import { StorageService } from '../../services/storage_service';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss'],
  providers: [StorageService]
})
export class LandingComponent implements OnInit {

Thanks for any suggestion :slight_smile:

I think that when you call the storage, it is not ready yet, so it returns undefined.
You can try to init the storage within app.component.ts or try to call storage on another component within ionViewWillEnter.

1 Like

:man_facepalming: so simple
I thought that if I call it on constructor that shouldn’t be a problem :sweat_smile:

@tokuhara thanks!