2017-10-17 31 views
0

登录到控制台时,以下代码在初始页面加载时产生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); 
} 

我明白这是异步的,但无法弄清楚如何获得初始页面加载从存储的价值,所以我可以在我的观点显示。我认为我正确地做了这件事... ...

+0

您需要使用ngoninit –

+0

您需要使用ngoninit。这是一个生命周期的钩子。 –

回答

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); 
} 
+0

我做了你的第一个例子,把它放在构造函数中,并接收'Uncaught(in promise):TypeError:无法读取'null'属性''。我知道当我刷新日志时,存储空间有价值。 – timgavin

+0

您可能需要等待平台就绪事件。我会更新我的答案。 – David

+0

它实际上是一个竞争条件,所以我正在做的是无论如何 - 变量不是从API中检索,直到页面加载后,所以我需要以另一种方式解决。我给你信贷,因为你的回答是我的问题的正确答案。谢谢! :) – timgavin

相关问题