在初始页面加载时无法获得本地存储值

时间:2017-10-17 19:03:58

标签: angular ionic-framework

当登录到控制台时,以下代码在初始页面加载时生成foo: undefined,但在后续刷新时生成foo: bar

ionViewDidLoad() {
    let foo = this.storage.get('foo');

    Promise.all([
        foo
    ]).then((result) => {
        this.foo = result[0];
        this.doSomething();
    });
}

doSomething() {
    console.log('foo: ' + this.foo);
}

我知道这是异步的,但无法弄清楚如何在初始页面加载时从存储中获取值,以便我可以在我的视图中显示它。我以为我这样做了吗?...

1 个答案:

答案 0 :(得分:0)

一些事情:你不需要将它包装在Promise.all中,因为它已经是一个承诺,而Promise.all则是将多个承诺合并为一个承诺。此外,您无需等待ionViewDidLoad从存储中获取内容,您可以在构造函数中执行此操作。我将您的代码移动到构造函数中,并向promise添加了成功和错误回调。我还使用async/await语法添加了另一个解决方案:

public foo;
constructor(...) {
  this.platform.ready().then(ready => {
    this.storage.get('foo').then(
      result => {
        this.foo = result[0];
        this.doSomething();
      },
      error => {
        console.error(error);
      },
    );

    this.doSomethingElse();
  }
}

doSomething() {
  console.log('foo: ' + this.foo);
}

async doSomethingElse() {
  let bar = await this.storage.get('bar');
  console.log('bar: ' + bar);
}