Bernard K.
Bernard K.

Reputation: 309

Using IONIC Storage Service, how to get and return stored JSON data?

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

Upvotes: 4

Views: 4996

Answers (2)

sebaferreras
sebaferreras

Reputation: 44669

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.

Upvotes: 7

Sajeetharan
Sajeetharan

Reputation: 222657

You need to return

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

Upvotes: 0

Related Questions