停止离子变化触发,直到从存储中加载值

Stop ion-change firing until values loaded from storage

在我的设置页面上有几个 ion-toggle。我有一个 onChange 方法,可以在切换时更新本地存储。相当标准的东西,当页面加载时,我检查现有值的存储,然后使用 ngModel.

将它们映射到切换的
<table>
    <tr>
        <td valign="middle" class="alertTitle"><p>Enable Notifications</p></td>
        <td><ion-toggle [(ngModel)]="notificationsEnabled" (ionChange)="toggleAlert('NOTIFICATIONS_ENABLED')"></ion-toggle></td>
    </tr>
    <tr>
        <td valign="middle" class="alertTitle"><p>Job Received</p></td>
        <td><ion-toggle [(ngModel)]="jobReceived" (ionChange)="toggleAlert('JOB_RECEIVED')"></ion-toggle></td>
    </tr>
    <tr>
        <td valign="middle" class="alertTitle"><p>Document Created</p></td>
        <td><ion-toggle [(ngModel)]="documentCreated" (ionChange)="toggleAlert('DOCUMENT_CREATED')"></ion-toggle></td>
    </tr>
    <tr>
        <td valign="middle" class="alertTitle"><p>Document Rejected</p></td>
        <td><ion-toggle [(ngModel)]="documentRejected" (ionChange)="toggleAlert('DOCUMENT_REJECTED')"></ion-toggle></td>
    </tr>
</table>

切换功能:

allAlertsLoaded(): boolean {
  return this.notificationsEnabledLoaded && this.jobReceivedLoaded && this.documentCreatedLoaded && this.documentRejectedLoaded;
}

toggle(alertConst: string) {
  if (!this.allAlertsLoaded()) {
    return;
  }

  this.storage.get(alertConst).then(res => {
    if (res) {
      this.storage.set(alertConst, false);
      return;
    }
    this.storage.set(alertConst, true);
  });
}

ngOnInit 中调用函数以加载现有值:

loadToggles() {
  this.storage.get(NOTIFICATIONS_ENABLED).then(res => {
    this.notificationsEnabled = res;
    this.notificationsEnabledLoaded = true;
  });
  this.storage.get(JOB_RECEIVED).then(res => {
    this.jobReceived = res;
    this.jobReceivedLoaded = true;
  });
  this.storage.get(DOCUMENT_CREATED).then(res => {
    this.documentCreated = res;
    this.documentCreatedLoaded = true;
  });
  this.storage.get(DOCUMENT_REJECTED).then(res => {
    this.documentRejected = res;
    this.documentRejectedLoaded = true;
  });
}

问题:当页面加载时,因为 stoage.get 是异步的,切换值默认为 false 然后当它们被加载时,它会在它们被更改时触发 toggle()。我需要切换功能不要 运行 直到它们全部加载。

我的解决方案:我为加载后设置为 true 的每个切换添加了一个 Loaded 变量。然后我在允许 toggle() 到 运行.

之前检查所有都已加载

这修复了前 3 个切换,但最后一个仍然在页面加载时关闭。

任何其他解决方案或我的错误都会很棒!

您可以考虑三种选择:

a) 适当编码并利用快速 js 异步引擎(简单且首选)

 <ion-toggle [(ngModel)]="notificationsEnabled" (ionChange)="toggle('NOTIFICATIONS_ENABLED', notificationsEnabled)"></ion-toggle>

toggle(alertConst: string, value: boolean) {
 this.storage.set(alertConst, value);
}

b) 使用async/await for force wait until Promise is resolved

You can find more reference here on implementation

c) 使用路由解析守卫在页面加载前完成

You can find more reference here on implementation