目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
你可以试试
import { Router, ActivatedRoute} from '@angular/router';
constructor(private router: Router, private activatedRoute:ActivatedRoute) {
console.log(activatedRoute.snapshot.url) // array of states
console.log(activatedRoute.snapshot.url[0].path) }
替代的方法
router.location.path(); this works only in browser console.
window。location。pathname给出了路径名。
其他回答
将Location注入组件并读取Location .path(); 你需要在某个地方添加ROUTER_DIRECTIVES,这样Angular才能解析Location。你需要在这个模块中添加import: [RouterModule]。
更新
在V3 (RC.3)路由器中,您可以注入ActivatedRoute,并使用它的snapshot属性访问更多细节。
constructor(private route:ActivatedRoute) {
console.log(route);
}
or
constructor(private router:Router) {
router.events.subscribe(...);
}
另见Angular 2的路由器事件侦听器
在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:
constructor(private router:Router,private segment:RouteSegment) {}
ngOnInit() {
this.router.navigate(["explore"],this.segment)
}
本机窗口对象也可以正常工作
console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);
注意:不要在服务器端渲染中使用这个
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}
这个是在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);
});
}