目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
本机窗口对象也可以正常工作
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);
注意:不要在服务器端渲染中使用这个
其他回答
Angular 2 rc2
router.urlTree.contains(router.createUrlTree(['/home']))
获取路由段:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {}
getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
如果你导入了路由器,那么你可以简单地使用一些东西
This.router.url === "/search"
否则执行以下操作
1)导入路由器
import { Router } from '@angular/router';
2)在构造函数中声明它的条目
constructor(private router: Router) { }
3)在你的工作中发挥它的价值
yourFunction(){
if(this.router.url === "/search"){
//some logic
}
}
@victor的回答帮助了我,这是和他一样的答案,但有一点细节,因为它可能会帮助到别人
新的V3路由器有一个url属性。
this.router.url === '/login'
给那些还在寻找这个的人。在Angular 2上。有几种方法。
constructor(private router: Router, private activatedRoute: ActivatedRoute){
// string path from root to current route. i.e /Root/CurrentRoute
router.url
// just the fragment of the current route. i.e. CurrentRoute
activatedRoute.url.value[0].path
// same as above with urlSegment[]
activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))
// same as above
activatedRoute.snapshot.url[0].path
// the url fragment from the parent route i.e. Root
// since the parent is an ActivatedRoute object, you can get the same using
activatedRoute.parent.url.value[0].path
}
引用:
https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html https://angular.io/docs/ts/latest/api/router/index/Router-class.html https://angular.io/docs/ts/latest/guide/router.html