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

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


当前回答

为了可靠地获得完整的当前路由,您可以使用这个

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);

其他回答

获取路由段:

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

constructor( route: ActivatedRoute) {}

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

角RC4:

你可以从@angular/ Router中导入Router

然后注入:

constructor(private router: Router ) {

}

然后调用它的URL参数:

console.log(this.router.url); //  /routename

下面是我在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>

Angular 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))

给那些还在寻找这个的人。在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