我一直在寻找一个好的方法来获取当前路由的路径名称。这是我能找到的最简单的方法。
我一直在寻找一个好的方法来获取当前路由的路径名称。这是我能找到的最简单的方法。
this.route.snapshot.firstChild.url[0].path
有更好的方法吗?谢谢!
我一直在寻找一个好的方法来获取当前路由的路径名称。这是我能找到的最简单的方法。
this.route.snapshot.firstChild.url[0].path
有更好的方法吗?谢谢!
感谢大家的回答。这是我发现我必须要做的事情。
router.events.subscribe((event: Event) => {
console.log(event);
if (event instanceof NavigationEnd ) {
this.currentUrl = event.url;
}
});
找到当前路径最简单的方法是直接使用
this.router.url
或者你可以像这样使用其事件,在每次路由器更改时检查当前路径。
this.router.events.subscribe((res) => {
console.log(this.router.url,"Current URL");
})
这里的 router
是在构造函数中创建实例的。
constructor(private router: Router){ ... }
constructor(private route:ActivatedRoute) {
console.log(route);
}
或者
constructor(private router:Router) {
router.events.subscribe(...);
}
router.events.subscribe((_: NavigationEnd) => this.currentUrl = _.url);
可以简写为: - ssuperczynski