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

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


当前回答

我面临的问题是,当用户在应用程序中导航或访问URL(或在特定URL上刷新)时,我需要URL路径来显示基于URL的子组件。

更重要的是,我想要一个可以在模板中使用的Observable,所以路由器。Url不是一个选项。和路由器。事件订阅,因为在组件模板初始化之前触发路由。

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

希望能有所帮助,祝你好运!

其他回答

给那些还在寻找这个的人。在Angular 2上。有几种方法。

constructor(private router: Router, private activatedRoute: ActivatedRoute){

   // string path from root to current route. i.e /Root/CurrentRoute
   router.url 

    // just the fragment of the current route. i.e. CurrentRoute
   activatedRoute.url.value[0].path

    // same as above with urlSegment[]
   activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))

   // same as above
   activatedRoute.snapshot.url[0].path

   // the url fragment from the parent route i.e. Root
   // since the parent is an ActivatedRoute object, you can get the same using 
   activatedRoute.parent.url.value[0].path
}

引用:

https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html https://angular.io/docs/ts/latest/api/router/index/Router-class.html https://angular.io/docs/ts/latest/guide/router.html

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

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

然后在构造函数中注入它

constructor(private route: ActivatedRoute){}

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

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

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

这个是在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 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))

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