【问题标题】:Angular: How to detect route changes in current component?Angular:如何检测当前组件的路由变化?
【发布时间】:2021-06-16 16:33:08
【问题描述】:

我想检测来自当前组件的路由并尝试了类似的方法。但它会在每条路线的开始和结束时触发。取而代之的是,当来自此DetailsComponent 的路由时,我如何检测路由更改?

export class DetailsComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
            }

            if (event instanceof NavigationEnd) {
            }
        });

   }
}

我需要在导航时从这个DetailsComponent获取url,如果url不是/employees,则进行操作。

【问题讨论】:

  • 还有其他人知道这个路由问题吗?
  • 不可能仅针对当前组件检测路由变化吗?

标签: javascript angular typescript routes angular-ui-router


【解决方案1】:

您的事件继续被检测到的原因是,当您的DetailsComponent 被销毁时,您并未取消订阅router.events

如果您只是取消订阅,它应该适合您:

export class DetailsComponent {
  private sub = this.router.events
    .pipe(
      filter(event => event instanceof NavigationStart),
      map(event => event as NavigationStart),  // appease typescript
      filter(event => event.url !== '/employees')
    )
    .subscribe(
      event => console.log('[DetailsComponent] NOT going to "/employees"!', event)
    );

  constructor(private router: Router) { }

  ngOnDestroy() {
    console.log('>> STOP listening to events for DetailsComponent');
    this.sub.unsubscribe();
  }

}

这是一个StackBlitz 示例。

【讨论】:

  • 非常感谢,我意识到了这一点,并按照您的建议取消了订阅。另一方面,我无法使用this.routerLocation 获取以前的网址。可能吗?在进入此详细信息页面之前,我只需要获取 previos url。
猜你喜欢
  • 2017-02-18
  • 2017-12-27
  • 2017-01-01
  • 2020-07-31
  • 2017-09-01
  • 2017-06-04
  • 2019-11-27
  • 2018-05-14
相关资源
最近更新 更多