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

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


当前回答

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

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

其他回答

获取路由段:

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }

对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login'; 

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

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

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

下面是我在Angular 2.3.1中工作的地方。

location: any;

constructor(private _router: Router) { 

      _router.events.subscribe((data:any) => { this.location = data.url; });

      console.warn(this.location);  // This should print only path e.g. "/home"
}

数据是一个对象,我们需要该对象中包含的url属性。所以我们在变量中获取这个值,我们也可以在HTML页面中使用这个变量。例如,我想显示一个div仅当用户在主页上。在这种情况下,我的路由器url值将是/home。所以我可以用下面的方式写一个div:

<div *ngIf="location == '/home'">
This is content for the home page.
</div>
this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});