繁体   English   中英

Angular:如何检测当前组件的路由变化?

[英]Angular: How to detect route changes in current component?

我想检测来自当前组件的路由并尝试了类似的方法。 但它会在每条路线的开始和结束时触发。 取而代之的是,当来自此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时进行操作。

继续检测到您的事件的原因是,当您的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示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM