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

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


当前回答

在组件文件中:

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

constructor(state: ActivatedRouteSnapshot) {
    console.log(state.path)
}

在路由文件中:

其他回答

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

新的V3路由器有一个url属性。

this.router.url === '/login'

这个是在Angular 11上测试的

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

使用这个

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);
    });

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