首页 > 解决方案 > 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');
        }

  }

你能帮我理解吗?谢谢,萨布丽娜

标签: angularionic-frameworklifecycledestroyondestroy

解决方案


将数据存储在服务中并在 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
}

推荐阅读