Javascript Ionic本机存储:storage.getItem()不工作
我正在使用离子本机存储来存储一些数据。当我使用Javascript Ionic本机存储:storage.getItem()不工作,javascript,angular,typescript,ionic-framework,cordova-nativestorage,Javascript,Angular,Typescript,Ionic Framework,Cordova Nativestorage,我正在使用离子本机存储来存储一些数据。当我使用setItem()和getItem()存储和检索数据时,它工作得非常好。但当我在中指定由getItem()检索的值时,则块。它在街区外不起作用 showDetails(名称:string){ this.stg.getItem(name).then(data=>{ 控制台日志(数据); this.pathName=data.name; this.type=data.type; this.positions=JSON.parse(data.positi
setItem()
和getItem()
存储和检索数据时,它工作得非常好。但当我在中指定由getItem()检索的值时,则块。它在街区外不起作用
showDetails(名称:string){
this.stg.getItem(name).then(data=>{
控制台日志(数据);
this.pathName=data.name;
this.type=data.type;
this.positions=JSON.parse(data.positions);
console.log(这个位置);
});
console.log(this.pathName+“”+this.type);
}
它看起来好像getItem
返回了一个承诺,如图所示。这意味着,This.pathName
将仅在您提供给然后
的回调中设置。如果这是异步的,那么在运行未定义行时,则未调用
回调,因此未设置任何值。这是异步编程的陷阱之一
更好的方法是将所有逻辑放在回调中:
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
}
这是可行的,但只有在里面。当我试图返回值或在之外使用它时,它有一个未定义的值。此问题已标记为重复,并提供了一些具有类似问题的其他问题。对于类似的问题,我建议你仔细检查一下?理解这一点是困难但重要的一步。