为什么我不能从从离子存储中获取值的函数返回字符串?

时间:2019-01-08 21:09:40

标签: angular ionic-framework

我正在尝试创建一种从存储中获取价值的方法,该方法可在我的整个应用程序中使用。我已经创建了服务并添加了功能...

getValue() {
    this.storage.get('value').then((val) => {
        return val;
    });
}

然后称呼它

const value = this.myService.getValue();

console.log('value=' + value);

但这是行不通的; console.log()仅返回value=[object Promise]

如何将值作为字符串返回?

1 个答案:

答案 0 :(得分:2)

您必须了解Storage get()方法是异步的,这意味着它返回Promise而不是直接返回值。这就是您需要链接.then()方法的原因,对吧?

链接.then(...)时,您将一个函数作为参数传递给它:

this.storage.get('values').then((value) => { ... });
//                              ^                ^
//                              |                |
//                              --------------------> This is a function

此函数是该诺言的处理程序。当您从中返回某些内容时,它将仅转换promise输出。但是,return不会冒出该功能。

因此,您的getValue()函数还必须返回一个Promise:

getValue() {
    return this.storage.get('value').then((val) => {
        return val;
    });
}

无论在何处使用它,都必须将其视为Promise(要获得价值的链.then()):

this.myService.getValue().then((value) => { console.log(value); });