使用IONIC Storage Service,如何获取和返回存储的JSON数据?

Ber*_* K. 3 ionic-framework ionic2 ionic3 angular

我是Ionic的新手.

我能够使用IONIC Storage Service存储A JSON对象(数据); 但是,当我尝试检索JSON数据时,我得到了未定义.

我感谢任何帮助 - 下面是我的代码:

Provider:storage-service.ts:我能够存储和输出数据,但是我无法返回数据:

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
        });
  }
 }
Run Code Online (Sandbox Code Playgroud)

我-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());
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助.

谢谢

seb*_*ras 5

由于离子存储基于承诺,您需要在服务中返回该承诺:

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

并且还用于then获取页面中的值

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

constructor(public storageService: StorageService) {

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

}
Run Code Online (Sandbox Code Playgroud)

在这里,您可以找到有关如何使用promises的更多信息.