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

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


当前回答

您可以使用ActivatedRoute来获取当前路由器

原文答案(RC版)

我在AngularJS谷歌Group上找到了一个解决方案,非常简单!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

这是最初的答案

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

其他回答

this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}
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);
    }
  });
}

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

要在angular 8中获取当前路由器,只需这样做

import {ActivatedRoute} from '@angular/router';

然后在构造函数中注入它

constructor(private route: ActivatedRoute){}

如果你想获取当前路由,那么使用这个route.url

如果你有多个名称路由,比如/home/pages/list你想访问单个,那么你可以访问每个,比如这个route。url。value[0]。path

值[0]会给你主页,值[1]会给你页面,值[2]会给你列表