【问题标题】:Stop ion-change firing until values loaded from storage停止离子变化激发,直到从存储中加载值
【发布时间】:2019-07-20 06:06:33
【问题描述】:

在我的设置页面上,我有几个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(),因为它们发生了变化。我需要在全部加载之前不要运行切换功能。

我的解决方案:我为每个切换开关添加了一个Loaded 变量,一旦它们被加载,它们就会设置为true。然后,我在允许 toggle() 运行之前检查所有内容是否已加载。

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

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

【问题讨论】:

    标签: javascript angular ionic-framework ionic4


    【解决方案1】:

    您可以考虑三个选项:

    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 强制等待,直到 Promise 解决

    你可以找到更多关于实现的参考here

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

    你可以找到更多关于实现的参考here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 2021-11-07
      • 2015-06-18
      • 2018-02-19
      相关资源
      最近更新 更多