目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
新建路由器>= 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"
}
其他回答
将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的路由器事件侦听器
要找到当前路由的父路由,你可以使用相对路由从路由器获取UrlTree:
var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});
然后得到主出口的分段:
tree.root.children[PRIMARY_OUTLET].segments;
本机窗口对象也可以正常工作
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 8中获取当前路由器,只需这样做
import {ActivatedRoute} from '@angular/router';
然后在构造函数中注入它
constructor(private route: ActivatedRoute){}
如果你想获取当前路由,那么使用这个route.url
如果你有多个名称路由,比如/home/pages/list你想访问单个,那么你可以访问每个,比如这个route。url。value[0]。path
值[0]会给你主页,值[1]会给你页面,值[2]会给你列表