我是 Ionic 平台的初学者,显然我在处理第一个应用程序的一小部分时遇到了一些麻烦。我想在按钮中有一个简单的计数器:单击此按钮时,计数器递增 1。然后我使用 Storage 保存该值,并使用“storage.get”在另一个页面中检索相同的值。
这是代码:
constructor(public storage:Storage, public platform: Platform){
this.storage = storage;
}
ionViewDidLoad() {
console.log("I'm alive!");
this.counter = this.storage.get("Count").then((data)=>{
console.log(data);
});
}
public counter = 0;
count(){
this.counter+=1;
this.storage.set("Count",this.counter);
}
当我重新打开应用程序时,我尝试使用存储的值继续递增计数器,但它又从 0 开始:如何使用存储的值递增计数器的变量?
感谢您的支持!
最佳答案
您正在将 this.counter 设置为 promise 调用。
改为这样做:
this.storage.get("Count").then((data)=>{
this.counter = data;
});
此外,一旦您在构造函数中将注入(inject)声明为 public,就无需在构造函数中再次设置它。它会自动与类的实例一起使用。基本上,您不需要这个。
this.storage = storage;
关于typescript - ionic 存储和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46157968/