Ionic 5 Angular 10 点击本地通知后按钮disabled属性异常问题
问题原因
Capacitor的LocalNotification原生事件回调默认运行在Angular的NgZone上下文之外,回调内执行路由跳转逻辑时,无法触发Angular的自动变更检测机制。你页面上按钮的[disabled]绑定依赖变更检测来同步最新状态,变更检测未激活的情况下,即使输入框newMsg的值发生变化,绑定的禁用状态也不会更新,因此按钮始终保持初始的禁用状态。
而点击Push Notification跳转时,应用通常是从后台唤醒/冷启动状态,Angular上下文完整,变更检测正常运行,因此逻辑无异常。
修复方案
将路由跳转逻辑包裹在NgZone.run()方法内,让逻辑回到Angular的变更检测上下文中执行即可:
- 首先导入并注入
NgZone:
import { NgZone } from '@angular/core'; import { NavigationExtras, Router } from '@angular/router'; import { ActionPerformed as LocalNotificationActionPerformed, LocalNotifications } from "@capacitor/local-notifications"; constructor (private router: Router, private ngZone: NgZone) {}
- 修改LocalNotification的监听回调:
LocalNotifications.addListener('localNotificationActionPerformed', (res: LocalNotificationActionPerformed) => { let params: NavigationExtras = { queryParams: {chatToEmployeeId: res.notification.extra.employeeId} } this.ngZone.run(() => { this.router.navigate(['/friend-list/chat'], params); }) })
可选优化建议
按钮的禁用判断可以直接绑定变量,无需额外写方法,减少不必要的函数执行开销:
<ion-button id="sendMsg" [disabled]="newMsg === ''" class="msg-btn" (click)="sendMessage()">
内容的提问来源于stack exchange,提问作者castamere
相关产品推荐
相关产品推荐

