angular - Angular 6 生命周期问题:页面显然无缘无故地被破坏
问题描述
我正在使用 Ionic 和 Angular 开发一个移动应用程序。我对 Angular 生命周期有疑问。我有一个带有日历的页面。日历有不同的视图:月、周和日。单击特定日期,您可以查看当天发生的事件。单击事件,应用程序将转到包含事件详细信息的页面。在此详细信息页面中,有一个返回日历的链接。
我面临的问题是:有时当我转到事件详细信息页面时,日历页面会被破坏,所以当我返回日历时,日历会重新初始化为默认值(关注今天和周视图)。这只是有时发生,我不明白为什么。
我认为只有在更改 url 参数时页面才会被破坏。例如:用户可以看到更多的日历,在url中传入哪个id;我了解日历页面在更改日历时会被破坏并重新初始化。问题是有时甚至在打开和事件然后返回日历页面时在同一个日历中也会发生这种情况。正如我所说,这种情况并非每次都会发生,而只是有时,而且我找不到模式。要从活动页面返回日历页面,我只需执行以下操作:
goToCalendar() {
if (this.userId) {
this.router.navigate(['/calendar/view/user/', this.userId]);
} else {
this.router.navigateByUrl('/calendar/view');
}
}
你能帮我理解吗?谢谢,萨布丽娜
解决方案
将数据存储在服务中并在 ngOnDestroy 中使用来存储变量并在 ngOnInit 中使用来恢复它
想象一下你有一个像
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ShareService{
data:any={}
constructor() { }
}
你想“记住”一个可变日期
在你的 page.calendar.component
date=new Date()
constructor(private shareService:ShareService){}
ngOnInit()
{
if (this.shareService.data.date)
this.date=this.shareService.data.date
}
ngOnDestroy()
{
this.shareService.data.date=this.date
}
推荐阅读
- python - 我无法理解如何用括号划分和输入结果
- php - 如何覆盖虚拟主机的 Apache ErrorLog
- php - 使用更新表的 IF 条件创建触发器的正确语法是什么?
- html - 如何使 Bootstrap 4 滑块中的图像响应?
- java - 有没有办法解决这个问题:第 45 行第 7 列路径 $.client[0].services 的预期名称
- node.js - 将 Discord 中的用户移至特定频道
- java - 我正在尝试从 Android 设备获取光传感器数据以在 Unity 应用程序中使用
- oop - OOP 与面向类的编程
- regex - 如何通过 Note 更改文本格式
- database-design - 如果大多数列都是唯一项,如何在 DynamoDB 表中定义键