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

时间:2017-04-12 04:58:41

标签: angular angular-routing angular2-observables

我一直在寻找获得当前路线路径名的好方法。这是我能找到的最简单的。

this.route.snapshot.firstChild.url[0].path

有更好的方法吗?谢谢!

3 个答案:

答案 0 :(得分:25)

感谢大家的回答。这是我发现我必须做的事情。

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

答案 1 :(得分:19)

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

this.router.url

或者你可以使用像这样的事件检查每个路由器更改的当前路径

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

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

constructor(private router: Router){ ... }

答案 2 :(得分:4)

constructor(private route:ActivatedRoute) {
  console.log(route);
}

constructor(private router:Router) {
  router.events.subscribe(...);
}