我正在使用离子本机存储来存储一些数据。当我使用setItem()
和getItem()
存储和检索数据时,它可以很好地工作。但是,当我为getItem()
块中的then
分配一个值时。它在块外不起作用。
showDetails(name: string) {
this.stg.getItem(name).then(data => {
console.log(data);
this.pathName = data.name;
this.type = data.type;
this.positions = JSON.parse(data.positions);
console.log(this.positions);
});
console.log(this.pathName + " " + this.type);
}
当我在控制台中打印数据时,我得到了结果,而且当我在then
块中打印单个值,但最后一个console.log
向我显示未定义未定义时,我也得到了结果。
答案 0 :(得分:3)
在documentation中可以看到getItem
似乎返回了一个Promise。这意味着this.pathName
仅在您提供给then
的回调中设置。如果这是异步的,那么到您未定义的行运行时,尚未调用then
回调,因此未设置任何值。这是异步编程的陷阱之一。
更好的方法是将所有逻辑都放在回调中:
showDetails(name: string) {
// get item could be async so do not assume your callback will be run immediately
this.stg.getItem(name).then(data => {
console.log(data);
this.pathName = data.name;
this.type = data.type;
this.positions = JSON.parse(data.positions);
console.log(this.positions);
// values now been set
console.log(this.pathName + " " + this.type);
});
// at this point no values have been set as the callback has not been called
console.log(this.pathName + " " + this.type); // so this line is undefined
}