使用 IONIC Storage Service,如何获取和 return 存储 JSON 数据?
Using IONIC Storage Service, how to get and return stored JSON data?
我是 Ionic 新手。
我可以使用 IONIC 存储服务存储 JSON 对象(数据);但是,当我尝试检索 JSON 数据时,我得到了 undefined.
感谢您对此提供的任何帮助 - 以下是我的代码:
提供商:存储-service.ts:
我可以存储和输出数据,但我不能 return 数据:
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
});
}
}
我的-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());
}
非常感谢对此的任何帮助。
谢谢
你需要return
public getStoredData() {
return this.storage.get('data').then((val) => {
return val;
});
}
}
由于 Ionic 存储基于承诺,因此您需要 return 服务中的承诺:
public getStoredData() {
return this.storage.get('data').then((val) => { // <-- Here!
console.dir(val);
return val;
});
}
并且还使用 then
获取页面中的值
import { StorageService } from "../../providers/storage-service";
constructor(public storageService: StorageService) {
this.storageService.getStoredData().then(data => {
console.dir(data); // <-- Like this!
});
}
Here 您可以找到更多关于如何使用承诺的信息。
我是 Ionic 新手。
我可以使用 IONIC 存储服务存储 JSON 对象(数据);但是,当我尝试检索 JSON 数据时,我得到了 undefined.
感谢您对此提供的任何帮助 - 以下是我的代码:
提供商:存储-service.ts: 我可以存储和输出数据,但我不能 return 数据:
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
});
}
}
我的-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());
}
非常感谢对此的任何帮助。
谢谢
你需要return
public getStoredData() {
return this.storage.get('data').then((val) => {
return val;
});
}
}
由于 Ionic 存储基于承诺,因此您需要 return 服务中的承诺:
public getStoredData() {
return this.storage.get('data').then((val) => { // <-- Here!
console.dir(val);
return val;
});
}
并且还使用 then
获取页面中的值
import { StorageService } from "../../providers/storage-service";
constructor(public storageService: StorageService) {
this.storageService.getStoredData().then(data => {
console.dir(data); // <-- Like this!
});
}
Here 您可以找到更多关于如何使用承诺的信息。