Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 49296

Ionic 5 Storage data not persistent between components

$
0
0

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:

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 49296


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>