How to get and return stored data - StorageService?

Hello,

I’m new to Ionic. I want to get and return the stored data, but it looks like I need to use Promise to make this code work and I do not know how to use Promise. I appreciate anyone who can look at my code below and give me advise on how to make this code work properly:

Provider: storage-service.ts:
I’m able to store and output data, but I cannot return the data:

import {Injectable} from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class StorageService {

constructor(public storage: Storage){}

public storeData (data) {
     this.storage.set('data', data);
  }

public getStoredData() {
    	this.storage.get('data').then((val) => {
    	console.dir(val);  //****** this outputs the object.
            return val;  //***** this returns undefined
     });
}

}


my-page.ts:

import {StorageService} from "../../providers/storage-service";

constructor(public storageService: StorageService) {

        //***** this outputs undefined, what I'm doing wrong?
        console.dir(this.storageService.getStoredData());
}
1 Like

try this

public getStoredData() {
    return this.storage.get('data');
}

Thank you - this worked; however, the data that is returned is an object. I tried this code and it does not work:
let user_hash=this.storageService.getStoredData()[‘user_hash’];
I also tried this and it does not work:
let user_hash=this.storageService.getStoredData().user_hash;
Could you please help on how do I get the value of the object name: user_hash?

refer this link i hope you will get all your answer here

You need to make the getStoredData() function promise and then when calling it, use .then to get your data out.

Get Data Function

getStorage(key: string): Promise<any> {
    return this.storage.get(key);
  }

Retrieving it

this.storage.getStorage('uid').then(uid => {
      // you can do anything here. I used uid as example because I use firebase and this saves me calls.
});

Don’t forget that not key and value are strings. You’ll need to use JSON.parse

1 Like

They should be DOMString which returns a string type. You wouldn’t want to put object, array, and/or number as your key.

1 Like