离子本机存储:storage.getItem()不起作用

时间:2019-07-27 21:01:19

标签: javascript angular typescript ionic-framework cordova-nativestorage

我正在使用离子本机存储来存储一些数据。当我使用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向我显示未定义未定义时,我也得到了结果。

1 个答案:

答案 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
  }