目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
Angular 2 rc2
router.urlTree.contains(router.createUrlTree(['/home']))
其他回答
将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的路由器事件侦听器
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.url.subscribe(value => {
// you may print value to see the actual object
// console.log(JSON.stringify(value));
this.isPreview = value[0].path === 'preview';
})
其中,路由器是ActivatedRoute的一个实例
如果你导入了路由器,那么你可以简单地使用一些东西
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的回答帮助了我,这是和他一样的答案,但有一点细节,因为它可能会帮助到别人
这适用于与authguard一起使用的情况
this.router.events.subscribe(event => {
if(event instanceof NavigationStart){
console.log('this is what your looking for ', event.url);
}
}
);