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

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


当前回答

对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login'; 

其他回答

这可能是你的答案,使用激活路由的params方法从你想要读取的URL/路由获取参数,下面是演示片段

import {ActivatedRoute} from '@angular/router'; 
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
             this.yourVariable = params['required_param_name'];
        });
    }
}

在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的代码。

this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});

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

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

你可以试试

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