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

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


当前回答

你可以试试

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

constructor(private router: Router, private activatedRoute:ActivatedRoute) {
console.log(activatedRoute.snapshot.url)  // array of states
console.log(activatedRoute.snapshot.url[0].path) }

替代的方法

router.location.path();   this works only in browser console. 

window。location。pathname给出了路径名。

其他回答

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

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

我面临的问题是,当用户在应用程序中导航或访问URL(或在特定URL上刷新)时,我需要URL路径来显示基于URL的子组件。

更重要的是,我想要一个可以在模板中使用的Observable,所以路由器。Url不是一个选项。和路由器。事件订阅,因为在组件模板初始化之前触发路由。

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

希望能有所帮助,祝你好运!

这可能是你的答案,使用激活路由的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'];
        });
    }
}

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

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

然后得到主出口的分段:

tree.root.children[PRIMARY_OUTLET].segments;