Ionic&Angular:从子页面修改模型后视图不刷新问题
Ionic 3.20 + Angular 5.2.9 视图不刷新问题排查
我目前正在用Ionic 3.20和Angular 5.2.9做开发,作为新手,最近碰到了一个头疼的问题:修改模型后视图没法刷新。
场景与代码详情
我的视图里有这么个元素:
<ion-item-sliding #slidingElement *ngFor="let item of this.myService.myList?.firstLevel.secondLevel">
对应的myService服务里有这两个函数:
public myList: Array; getListOfData(): Observable { return this.http.get(`service_endpoint_url`); } retrieveListOfData() { this.getListOfData().subscribe((result) => { this.myList = result; this.counter = this.myList['firstLevel'].length; }); }
首次加载页面时,我在ngOnInit里调用this.myService.retrieveListOfData(),视图能正常渲染。当我对列表里的某一项执行操作后,列表应该刷新(把该项移除),我是这么实现的:
如果在列表所在页面内执行这段代码,功能完全正常:
this.actionService.DoAction().subscribe((result) => { if(result == 'success') { this.myService.retrieveListOfData(); } });
但如果是在列表项的详情页面(点击列表项进入的子页面)执行操作,控制台显示this.myList已经修改了,但返回列表页面时视图就是不重新渲染,代码如下:
this.actionService.DoAction().subscribe((result) => { if(result == 'success') { this.myService.retrieveListOfData(); // 从详情页面返回列表页面 this.app.getRootNav().popToRoot(); } });
我一开始怀疑是不是和Zone有关?想知道怎么从详情页面正确刷新列表项?
2018-05-14 更新:问题解决
我终于找到问题根源了!因为我们项目用了模块懒加载,导致服务没有在组件间以单例形式共享——每个组件都运行了独立的服务实例!
我采用了ForRoot模式的解决方案来确保服务是单例的。另外我也发现之前的术语表述有误:我提到的组件并不是Angular概念里的兄弟组件,这里特意说明一下,同时保留Joshua的回答作为正确答案。
内容的提问来源于stack exchange,提问作者Marko Kastelec
相关产品推荐
相关产品推荐

