在Angular 4中获取当前路径路径名称的最简单方法是什么?

jar*_*ink 18 angular-routing angular

我一直在寻找获得当前路线路径名的好方法.这是我能找到的最容易的.

this.route.snapshot.firstChild.url[0].path
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?谢谢!

jar*_*ink 28

谢谢大家的答案.这是我发现我必须做的事情.

router.events.subscribe((event: Event) => {
  console.log(event);
  if (event instanceof NavigationEnd ) {
    this.currentUrl = event.url;
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 或更短:`router.events.subscribe((_:NavigationEnd)=> this.currentUrl = _.url);` (2认同)

Par*_*ain 25

找到当前路径的最简单方法是直接使用

this.router.url
Run Code Online (Sandbox Code Playgroud)

或者您可以使用此类事件检查每个路由器更改的当前路径

this.router.events.subscribe((res) => { 
    console.log(this.router.url,"Current URL");
})
Run Code Online (Sandbox Code Playgroud)

其中,router这里例如在构造函数中创建这样的

constructor(private router: Router){ ... }
Run Code Online (Sandbox Code Playgroud)