如何在提交新数据之前清除离子存储

问题描述 投票:0回答:1

我正在使用inappbrowser中的webapp创建一个离子应用程序。我创建了一个单独的离子登录表单,将凭据发送到webapp的登录表单,以便我可以登录webapp。

这是我当前代码的流程:

如果用户在存储中保存了凭据,请打开webapp并自动登录用户;否则,请留在登录页面上。

但问题是,如果每次用户有新登录时清除存储,它都会返回一个空值。

另外,我不太确定我的代码是否是一个好习惯,另一种方法是什么?

userInput: string = "";
passInput: string = "";
userKey:string = 'username';
passKey:string = 'password';

constructor(
  private platform: Platform,
  private iab: InAppBrowser,
  private storage: Storage
) { this.init(); }

init() {
  let promiseList = [];

  Promise.all([
    this.storage.get(this.userKey).then((username) => {
      console.log('Retrieved username is', username);
      promiseList.push(username)
    }),
    this.storage.get(this.passKey).then((password) => {
      console.log('Retrieved password is', password);
      promiseList.push(password)
    })
  ]).then(() => {
    console.log('promiseList', promiseList)
    if (validated) { this.openWebApp(promiseList) }
    else { //remain in the login page }
  })
}

login() {
  // this.storage.clear()
  this.storage.set(this.userKey, this.userInput)
  this.storage.set(this.passKey, this.passInput)
  this.init();
}

openWebApp(credentials) {
  console.log('credentials', credentials, credentials[0], credentials[1])
  this.platform.ready().then(() => {
    const browser = this.iab.create('https://www.mywebapp.com/login', '_blank', {location:'no', footer:'no', zoom:'no', usewkwebview:'yes', toolbar:'no'});

    browser.on('loadstop').subscribe(event => {
    browser.show();

    browser.executeScript({
        code: `document.getElementById("usernameInput").value=${credentials[0]} document.getElementById("passwordInput").value=${credentials[1]} document.getElementById("submitBtn").click()`
    })
  });
});

这就是我想要实现的目标:

如果用户使用新凭据再次登录,请清除旧凭据并保存新凭据。

angular ionic-framework inappbrowser ionic4 ionic-storage
1个回答
1
投票

Ionic Storage函数通常会返回Promises ...所以你需要等待这些Promise来解决之前做其他事情...例如:

async login() {
  await this.storage.clear();
  await this.storage.set(this.userKey, this.userInput);
  await this.storage.set(this.passKey, this.passInput);
  this.init();
}
© www.soinside.com 2019 - 2024. All rights reserved.