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

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


当前回答

你可以使用this.activatedRoute.pathFromRoot。

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

在pathFromRoot的帮助下,您可以获得父URL的列表,并检查URL中所需的部分是否与您的条件匹配。

欲了解更多信息,请查看本文http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ 或者从NPM安装ng2-router-helper

npm install ng2-router-helper

其他回答

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

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

这适用于与authguard一起使用的情况

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );

这个是在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) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
  });
}
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}