typescript - ionic 存储和变量

标签 typescript ionic-framework ionic-native

我是 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/

相关文章:

angular - Ionic 4 native 插件地理定位给我 "Module not found: Error: Can' t 解析 'rxjs/Observable'"

vue.js - ionic 原生角度示例代码到 vuejs

cordova - ionic 构建android的错误: copyFileSync: could not write to dest file

javascript - 带有动态标题和单元格的 Angular 7 Material 表

android - $cordovaFile removeFile & checkDir 错误 5 (ENCODING_ERR)

javascript - react Antd : How to remove spacing between vertical divider and any content right next to it?

android - ionic 构建工具已安装但收到错误 "No installed build tools found. Install the Android build tools version 19.1.0 or higher."

javascript - 向下滑动事件未触发 - ionic 框架

javascript - 在 typescript 中隐式引用另一个内部模块

typescript - 如何使用 VS Code 在 .vue 文件中使用 Typescript?