【问题标题】:Angular 6 lifecycle problem: page gets destroyed apparently with no reasonAngular 6 生命周期问题:页面显然无缘无故地被破坏
【发布时间】:2020-09-15 08:46:05
【问题描述】:

我正在使用 Ionic 和 Angular 开发一个移动应用程序。我对 Angular 生命周期有疑问。 我有一个带有日历的页面。日历有不同的视图:月、周和日。单击特定日期,您可以查看当天发生的事件。单击事件,应用程序将转到包含事件详细信息的页面。在此详细信息页面中,有一个返回日历的链接。

我面临的问题是:有时当我转到事件详细信息页面时,日历页面会被破坏,所以当我返回日历时,日历会重新初始化为默认值(关注今天和星期看法)。这只是偶尔发生,我不明白为什么。

我认为只有在更改 url 参数时页面才会被破坏。例如:用户可以看到更多的日历,在url中传入哪个id;我了解更改日历时日历页面会被破坏并重新初始化。问题是有时甚至在打开和事件然后返回日历页面时在同一个日历中也会发生这种情况。正如我所说,这种情况并非每次都会发生,而只是有时,而且我找不到模式。 要从活动页面返回日历页面,我只需这样做:

 goToCalendar() {
        if (this.userId) {
          this.router.navigate(['/calendar/view/user/', this.userId]);
        } else {
          this.router.navigateByUrl('/calendar/view');
        }

  }

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

【问题讨论】:

  • 你使用的是哪个离子版本?
  • 你能提供一个stackblit吗?如果没有完整的细节,这将是猜测。
  • @Arikael 我正在使用 ionic 4.11.10

标签: angular ionic-framework lifecycle destroy ondestroy


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2011-07-03
    • 1970-01-01
    • 2014-11-14
    • 2020-08-10
    • 2019-11-19
    • 2018-04-09
    • 2018-02-26
    相关资源
    最近更新 更多