How to get and return stored data - StorageService?


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';

export class StorageService {

constructor(public storage: Storage){}

public storeData (data) {'data', data);

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



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

constructor(public storageService: StorageService) {

        //***** this outputs undefined, what I'm doing wrong?
1 Like

try this

public getStoredData() {

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> {

Retrieving it'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