目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
这个是在Angular 11上测试的
constructor(private router: Router) {
this.router.events
.pipe(filter((event: any) => event instanceof NavigationEnd))
.subscribe((event: any) => {
this.currentRoute = event.url;
console.log(event);
});
}
其他回答
在组件文件中:
import {ActivatedRouteSnapshot} from '@angular/router';
constructor(state: ActivatedRouteSnapshot) {
console.log(state.path)
}
在路由文件中:
新建路由器>= RC.3
最好和一个简单的方法来做到这一点是!
import { Router } from '@angular/router';
constructor(router: Router) {
router.events.subscribe((url:any) => console.log(url));
console.log(router.url); // to print only path eg:"/login"
}
如果你不能访问路由器,这是一个更简单的方法。url(例如,如果你使用skipLocationChange),你可以使用以下:
import { Location } from '@angular/common';
constructor(private readonly location: Location) {}
ngOnInit(): void {
console.log(this.location.path());
}
this.router.events.subscribe((val) => {
const currentPage = this.router.url; // Current page route
const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
为了可靠地获得完整的当前路由,您可以使用这个
this.router.events.subscribe(
(event: any) => {
if (event instanceof NavigationEnd) {
console.log('this.router.url', this.router.url);
}
}
);