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

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


当前回答

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

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

其他回答

使用这个

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

constructor(private router: Router) {
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            console.log(event);
        });
}

主要是。ts进口

import 'rxjs/add/operator/filter';

EDIT

现代的方式

import {filter} from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });

你可以试试

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给出了路径名。

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

您可以使用ActivatedRoute来获取当前路由器

原文答案(RC版)

我在AngularJS谷歌Group上找到了一个解决方案,非常简单!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

这是最初的答案

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

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

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