【发布时间】:2017-09-07 04:46:07
【问题描述】:
我有以下代码从 Ionic2 原生 AppPreferences 中获取城市:
import { AppPreferences } from '@ionic-native/app-preferences';
constructor(public appPreferences: AppPreferences) {
console.log("The city is : " + this.loadPreferences("selectedCity"));
}
loadPreferences(preferenceKey: any){
this.appPreferences.fetch(preferenceKey).then((res) => { return res; });
}
里面 .then((res) => {console.log});该值已打印并且工作正常。但是当我返回值或将其分配给某个变量时,我得到的值是“城市是:未定义”。我做错了什么吗?
提前致谢和问候。
【问题讨论】:
-
fetch 方法是异步的,只有在构造函数完成后才会运行。你能给出一个失败的代码示例吗?这是您要运行的代码吗?
-
是的,这是我正在尝试运行的实际代码
-
想想每一行代码以及它何时执行
-
我明白了。正如@misha130 所说,考虑每一行。在我从异步方法获得结果之前打印以下行: console.log("The city is : " + this.loadPreferences("selectedCity"));我稍微改变了我的代码。现在,当我在异步函数中获得结果时,我运行我的代码。非常感谢
标签: angular typescript ionic2