如何在 angular 的同一组件中加载 URL 发生变化的页面内容?

How can I load content on page with a change in URL in the same component in angular?

我正在尝试让页面在 URL 更改时加载同一组件中的一些内容。

myComponent.ts

ngOnInit(){
  this.router.events.subscribe(res=> {
    if (this.router.url.split('?')[0].split("/").pop() === 'invitations'){
      console.log('do something');
    }
  }
}

myModule.ts

const routes: Routes = [
           { 
             path: 'fancy_app', 
             component: myComponent,
             children:[
               {path: 'invitations', component: myComponent}
             ]
           }
];

当我这样做时,当我第一次尝试访问路由:fancy_app/invitations 时,我注意到 'do something' 没有加载。但是,当我再次单击 link 时,它起作用了。所以我猜 ngOnInit 不是这个地方?我如何确保它在我第一次访问 URL 时加载?

好的,我把它放在它工作的构造函数中。仍然不清楚为什么这对 ngOnInit 不起作用。据我了解,在构造函数实例化 class 之后调用 ngOnInit。我试图避免使用构造函数。有人可以告诉我为什么 ngOnInit 在我第一次尝试访问 URL 时不起作用吗?