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

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


当前回答

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

其他回答

这很简单,在angular 2中,你只需要像这样导入Router库:

import { Router } from '@angular/router';

然后在组件或服务的构造函数中,你必须像这样实例化它:

constructor(private _router: Router) {}

然后在代码的任何部分,函数、方法、构造等等:

      this._router.events
        .subscribe(
            (url:any) => {
                let _ruta = "";
                url.url.split("/").forEach(element => {
                    if(element!=="" && _ruta==="")
                        _ruta="/"+element;  
                });
                console.log("route: "+_ruta); //<<<---- Root path
                console.log("to URL:"+url.url); //<<<---- Destination URL                    
                console.log("from URL:"+this._router.url);//<<<---- Current URL
            }); 

新建路由器>= RC.3

最好和一个简单的方法来做到这一点是!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}

将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的路由器事件侦听器

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

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

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

然后得到主出口的分段:

tree.root.children[PRIMARY_OUTLET].segments;