Javascript 停止离子交换激发,直到从存储器加载值

Javascript 停止离子交换激发,直到从存储器加载值,javascript,angular,ionic-framework,ionic4,Javascript,Angular,Ionic Framework,Ionic4,在我的设置页面上,我有几个离子开关。我有一个onChange方法,在切换本地存储时更新它们。相当标准的东西,当加载页面时,我检查存储中的现有值,然后使用ngModel将它们映射到切换 <table> <tr> <td valign="middle" class="alertTitle"><p>Enable Notifications</p></td> <td><ion

在我的设置页面上,我有几个离子开关。我有一个
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>
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个切换,但最后一个仍在页面加载时关闭


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

您可以考虑以下三种选择:

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


切换(alertConst:string,value:boolean){
this.storage.set(alertConst,value);
}
b)使用async/wait强制等待,直到承诺得到解决

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

toggle(alertConst: string, value: boolean) {
 this.storage.set(alertConst, value);
}
您可以找到更多关于实现的参考资料

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

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

toggle(alertConst: string, value: boolean) {
 this.storage.set(alertConst, value);
}
您可以找到更多关于实现的参考资料