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

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


当前回答

import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}

其他回答

在angular 2.2.1中(在一个基于angar2 -webpack-starter的项目中)是这样工作的:

export class AppComponent {
  subscription: Subscription;
  activeUrl: string;

  constructor(public appState: AppState,
              private router: Router) {
    console.log('[app] constructor AppComponent');
  }

  ngOnInit() {
    console.log('[app] ngOnInit');
    let _this = this;
    this.subscription = this.router.events.subscribe(function (s) {
      if (s instanceof NavigationEnd) {
        _this.activeUrl = s.urlAfterRedirects;
      }
    });
  }

  ngOnDestroy() {
    console.log('[app] ngOnDestroy: ');
    this.subscription.unsubscribe();
  }
}

在AppComponent的模板中,你可以使用{{activeUrl}}。

这个解决方案的灵感来自于RouterLinkActive的代码。

你可以试试

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

可以在.ts文件中使用

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

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });

简单的方法

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

这个是在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);
   });
 }