【发布时间】: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