Angular路由:获取组件状态中的最新路由link

Angular Routing: Retrieving the latest route link inside the component state

为了提供一个最小的示例,假设我在 RouterModule.forRoot 中指定了以下两条路由,两者都 linked 到同一组件 SomeComponent.

const routes: Routes = [{ path: 'one-path',  component: SomeComponent },
{ path: 'another-path', component: SomeComponent }];

在应用 html 模板中,我有两个路由器 link 以及路由器插座

<a routerLink="/one-path">someLink</a> 
<a routerLink="/another-path">anotherLink</a>
...
<router-outlet> </router-outlet>

我想要的是作为 SomeComponent 状态的一部分的最后一个路由器 link 路径,由于该路径在页面上呈现组件。目的是根据使用的 link 显示略有不同的视图。

export class SomeComponent implements OnInit {

  let route_path = ... //this should either be 'one-path' or 'another-path' depending on which link was clicked

}

如何实现?

您需要订阅激活的路由 url observable。当组件初始化时,route_path 将是 'one-path' 或 'another-path',具体取决于单击了哪个 link 或者您是否在主路线上。

export class SomeComponent implements OnInit { 
    route_path ='';  

    constructor(private route: ActivatedRoute) { }

   ngOnInit() {

    this.route.url.subscribe((url) => {
         this.route_path = (url.length > 0 )? url[url.length-1].path: '';
      });

   }
}