4

I’m new to Ionic.

I'm able to store A JSON object (data) using IONIC Storage Service; however, when I try to retrieve the JSON data, I get undefined.

I appreciate any help on this - below is my code:

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());
}

Any help on this is greatly appreciated.

Thank you

0

2 Answers 2

7

Since Ionic storage is based on promises, you need to return that promise in the service:

public getStoredData() {
  return this.storage.get('data').then((val) => { // <-- Here!
    console.dir(val);
    return val;
  });
}

And also use then to get the value in your page

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

constructor(public storageService: StorageService) {

  this.storageService.getStoredData().then(data => {
    console.dir(data); // <-- Like this!
  });

}

Here you can find some more information about how to use promises.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this worked, but my code looks messy. Is there a better way to do this: constructor(public storageService: StorageService) { this.storageService.getStoredData() .then(data => { let hash = data.hash; let params = {'user_hash': user_hash}; this.eventService.getEvents(headers, params) .subscribe((data: any) => { this.events = data; }, (error: any) => { }); }); } }
I think your code looks good. It's hard to know without some more context to be honest.
Storageservice.ts loadData(key:string) { return this.storage.get(key).then((val) => { return val; }); } home.ts this.interservice.loadData('auth').then((res) => { this.activeuser = res; }); console.log("Home",this.activeuser) console return undefined. what's my mistake.
0

You need to return

public getStoredData() {
  return this.storage.get('data').then((val) => {
           return val;  
   });
  }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.