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

How to clear the ionic storage before submitting the new data

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

这是我当前代码的流程:

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

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

另外,我不太确定我的代码是否是一个好的做法,还有什么其他的方法吗?

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()`
    })
  });
});

这是我想要实现的目标:

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

Ionic Storage 通常使用 return Promise...所以您需要等待这些 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();
}