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

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


当前回答

router.events。订阅(e => { if (e instanceof NavigationEnd) { 这一点。currentUrl = e.url; } });

其他回答

为了可靠地获得完整的当前路由,您可以使用这个

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.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 14中,如果你这样做

this.router.url

它总是会返回'/'

您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。

import { Location } from '@angular/common';

constructor(private location: Location) { }

ngOnInit(): void {
    console.log(this.location.path());  // returns path

}

我面临的问题是,当用户在应用程序中导航或访问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)
);

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

到目前为止,我的路径如下-

this.router.url.subscribe(value => {
    // you may print value to see the actual object
    // console.log(JSON.stringify(value));
    this.isPreview = value[0].path === 'preview';
})

其中,路由器是ActivatedRoute的一个实例