Ionic5+Angular页面绑定Person对象 WebSQL更新后视图不刷新求助
问题根因
WebSQL的异步回调执行上下文不在Angular的NgZone管理范围内,你在回调中更新Person对象属性后,Angular的变更检测机制未被触发,因此视图不会同步更新,只有后续用户交互(例如点击菜单)触发全局变更检测后,才会将最新值渲染到页面。
解决方案
方案1:通过NgZone将更新逻辑放回Angular执行上下文
这是最推荐的处理方式,只需将回调内的赋值逻辑包裹在ngZone.run()中,执行完成后会自动触发变更检测:
- 首先在组件中注入
NgZone
import { NgZone } from '@angular/core'; // 组件类构造函数中注入 constructor(private ngZone: NgZone) {}
- 修改回调函数逻辑
jsonData["SelectFunctionInSuccess"] = (result)=>{ this.ngZone.run(() => { this.Person.Id = result[0].Id; this.Person.Code = result[0].Code; this.Person.Name = result[0].Name; this.Person.Family = result[0].Family; }) }
方案2:手动触发变更检测
也可以注入ChangeDetectorRef,赋值完成后手动触发当前组件的变更检测:
- 首先在组件中注入
ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core'; // 组件类构造函数中注入 constructor(private cdr: ChangeDetectorRef) {}
- 修改回调函数逻辑
jsonData["SelectFunctionInSuccess"] = (result)=>{ this.Person.Id = result[0].Id; this.Person.Code = result[0].Code; this.Person.Name = result[0].Name; this.Person.Family = result[0].Family; this.cdr.detectChanges(); }
内容的提问来源于stack exchange,提问作者hasan
相关产品推荐
相关产品推荐

