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

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


当前回答

角RC4:

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

然后注入:

constructor(private router: Router ) {

}

然后调用它的URL参数:

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

其他回答

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

新建路由器>= 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"
}

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

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

在Angular 14中,如果你这样做

this.router.url

它总是会返回'/'

您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。

import { Location } from '@angular/common';

constructor(private location: Location) { }

ngOnInit(): void {
    console.log(this.location.path());  // returns path

}

使用这个

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