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

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


当前回答

如果你不能访问路由器,这是一个更简单的方法。url(例如,如果你使用skipLocationChange),你可以使用以下:

import { Location } from '@angular/common';    
constructor(private readonly location: Location) {}
    
ngOnInit(): void {
  console.log(this.location.path());
}

其他回答

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

constructor(private router: Router) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
  });
}

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

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

如果你不能访问路由器,这是一个更简单的方法。url(例如,如果你使用skipLocationChange),你可以使用以下:

import { Location } from '@angular/common';    
constructor(private readonly location: Location) {}
    
ngOnInit(): void {
  console.log(this.location.path());
}
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}