securestorage离子在记录后无法访问

时间:2018-04-16 15:58:00

标签: angular ionic-framework mobile

我看了Ionic,检查了这个code,这里也是Sample,我总是失败。 :(。 这是我的代码:

getHotelInfByKey(value);

上面的代码在" .then(...)"中运行toast时正确返回Key。但是,当试图在其他地方访问时,比如showData(),无法工作,返回" undefined"。

为什么" this.data = storage"不在"创建(' demoapp')。然后(...)"?

如何在其他网页中访问存储在' demmoapp' ?

如果有一个教程我可以遵循修复,请与我分享。 我现在从离子开始,开始研究角度和离子,但我没有为这个问题做好准备。

继续:

export class HomePage {
 private secureStorage: SecureStorage;
 private data: SecureStorageObject;
 private msg: string;
 constructor(public navCtrl: NavController, public platform: Platform, 
 private toast: ToastController) {
if (platform.is('cordova')) {
  platform.ready().then(() => {

    this.secureStorage = new SecureStorage();
    this.secureStorage.create('demoapp').then(
      (storage: SecureStorageObject) => {
        this.toast.create({message: 'Storage is ready!',position: 'bottom', duration: 3000}).present();
        this.data = storage;
        this.data.set('teste','chave')
          .then(
            data => {
              this.setMsg("gravou");
              this.toast.create({message: "enable ="+this.msg,position: 'bottom', duration: 3000}).present();
              this.data.get('teste')
                .then(
                  data => {
                    this.setMsg(data);
                    this.toast.create({message: "content="+this.msg,position: 'bottom', duration: 3000}).present();
                  },
                  error => {
                    // do nothing - it just means it doesn't exist
                  }
                );
            },
            error => {
              // do nothing - it just means it doesn't exist
            }
          );
      },
      error => console.log(error)
    );
  });
} else {
  this.toast.create({message: "not enable",position: 'bottom', duration: 3000}).present();
}
}
setMsg(msg: string) {
  this.msg = msg;
}

getMsg(){
  return this.data.get('teste');
}

showData() {
  this.toast.create({message: "show ="+this.getMsg(),position: 'bottom', duration: 3000}).present();
}

所有在一个mac os x sierra。

Thks

1 个答案:

答案 0 :(得分:0)

我没有时间复制这个问题,所以如果我找到时间,我会添加更多。

我注意到你在相同的范围内使用了两次变量数据。

嵌套承诺时应更改变量名称。

    this.data.set('teste','chave')
      .then(
        data => {

          // !! FIRST DEFINITION OF DATA  ^^   

          this.setMsg("gravou");
          this.toast.create({message: "enable ="+this.msg,position: 'bottom', duration: 3000}).present();
          this.data.get('teste')
            .then(
              data => {

                // !! SECOND DEFINITION OF DATA ^^

                this.setMsg(data);
                this.toast.create({message: "content="+this.msg,position: 'bottom', duration: 3000}).present();
              },
              error => {
                // do nothing - it just means it doesn't exist
              }
            );
        },
        error => {
          // do nothing - it just means it doesn't exist
        }
      );

另外,你在调试吗?你是在单步执行代码吗?