目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
给那些还在寻找这个的人。在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
其他回答
这可能是你的答案,使用激活路由的params方法从你想要读取的URL/路由获取参数,下面是演示片段
import {ActivatedRoute} from '@angular/router';
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
this.yourVariable = params['required_param_name'];
});
}
}
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.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的一个实例
Angular 2 rc2
router.urlTree.contains(router.createUrlTree(['/home']))
为了可靠地获得完整的当前路由,您可以使用这个
this.router.events.subscribe(
(event: any) => {
if (event instanceof NavigationEnd) {
console.log('this.router.url', this.router.url);
}
}
);