目前的文档只讨论了获取路由参数,而不是实际的路由段。

例如,如果我想找到当前路由的父,这是怎么可能的?


当前回答

在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:

constructor(private router:Router,private segment:RouteSegment) {}

ngOnInit() {
  this.router.navigate(["explore"],this.segment)
}

其他回答

到目前为止,我的路径如下-

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的一个实例

要找到当前路由的父路由,你可以使用相对路由从路由器获取UrlTree:

var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});

然后得到主出口的分段:

tree.root.children[PRIMARY_OUTLET].segments;

我也有同样的问题

this.router.url

我用查询参数获取当前路由。我做的一个变通方法是使用这个:

this.router.url.split('?')[0]

这不是一个很好的解决方案,但很有帮助。

在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:

constructor(private router:Router,private segment:RouteSegment) {}

ngOnInit() {
  this.router.navigate(["explore"],this.segment)
}

在Angular 14中,如果你这样做

this.router.url

它总是会返回'/'

您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。

import { Location } from '@angular/common';

constructor(private location: Location) { }

ngOnInit(): void {
    console.log(this.location.path());  // returns path

}