【问题标题】:Angular: How to check change in queryParams before ngOnDestroy is calledAngular:如何在调用 ngOnDestroy 之前检查 queryParams 的变化
【发布时间】:2021-06-27 22:35:04
【问题描述】:

我想根据当前路由的变化有条件地执行ngOnDestroy中的一些代码。

Route 由/foo 更改为/login?logout=true,并且此更改是在 Foo 组件之外触发的。

ngOnInit 中,我订阅了queryParam 更改,以正确更新loggingOut 标志。

我的问题是,ngOnDestroy 在 queryParam 的下一个处理程序之前被调用,所以 loggingOut 的值不正确。

export class FooComponent implements OnInit, OnDestroy {
    
    loggingOut = false;

    constructor(private route: ActivatedRoute) {}

    ngOnInit(): void {
        this.route.queryParamMap.subscribe(queryParams => {
            this.loggingOut = queryParams.get('logout') === 'true';
        });

    }

    ngOnDestroy(): void {
        if (this.loggingOut) {
            // do this
        } else {
            // do that
        }
    }
}

似乎这是生命周期 POV 的预期行为,所以有以下问题:

  • 有没有办法在调用ngOnDestory 之前检查路由变化?

如果可能,请添加指向文档的链接,描述如何针对导航更改调用生命周期挂钩(尤其是 ngOnDestory)?

谢谢。

【问题讨论】:

  • Angular 路由不是这样工作的。您必须在注销页面上“执行此操作”,并在替代路线上“执行此操作”。
  • 能否请您添加一个指向某些资源的链接,这样可以更详细地解释一下?

标签: javascript angular typescript angular2-routing


【解决方案1】:

我的问题是,在 queryParam 的下一个处理程序之前调用 ngOnDestroy

componentDestroyed = false;

ngOnInit(): void {
    this.route.queryParamMap.subscribe(queryParams => {
        if (!this.componentDestroyed)
            this.loggingOut = queryParams.get('logout') === 'true';
        else {
           // Do here what you wanted to do in ngOnDestroy
        }
    });

}

ngOnDestroy(): void {
    this.componentDestroyed = true;
}

这能解决您的问题吗?

【讨论】:

  • 不幸的是不是,因为在“那个”分支上,我正在保存组件状态以存储并且不想每次路由参数更改时都这样做,无论如何谢谢
猜你喜欢
  • 2020-04-02
  • 2019-01-24
  • 1970-01-01
  • 2021-12-12
  • 2021-01-09
  • 2017-04-20
  • 2014-02-02
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多