【问题标题】:Ionic2 AppPreferences undefinedIonic2 AppPreferences 未定义
【发布时间】: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


【解决方案1】:

我明白了。正如@misha130 所说,考虑每一行。在我从 async 方法获得结果之前打印以下行:

console.log("The city is : " + this.loadPreferences("selectedCity"));

我稍微更改了我的代码。现在,当我在异步函数中获得结果时,我运行我的代码。非常感谢

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2017-04-27
    • 2016-05-22
    • 2018-01-25
    相关资源
    最近更新 更多