如何获取当前路线

Posted

技术标签:

【中文标题】如何获取当前路线【英文标题】:How to get current route 【发布时间】:2016-04-08 11:02:46 【问题描述】:

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

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

【问题讨论】:

window.location.pathname @dhacke window.location 的问题是,如果将来他们想要实现服务器端渲染,他们将面临一些困难,因为 Node.js 服务器上不存在 window ,但他们需要使用 Angular 标准方法来访问路由,并且在服务器和浏览器上都可以。 是的,有道理。那些使用或计划使用服务器端渲染的人应该考虑到这一点。 【参考方案1】:

如果您无法访问 router.url(例如,如果您使用了 skipLocationChange),则可以使用以下更简单的方法:

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

【讨论】:

【参考方案2】:

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

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

【讨论】:

【参考方案3】:

在 Angular2 Rc1 中,您可以注入 RouteSegment,然后将其传递给 .navigate() 方法:

constructor(private router:Router,private segment:RouteSegment) 

ngOnInit() 
  this.router.navigate(["explore"],this.segment)

【讨论】:

【参考方案4】:

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

【讨论】:

这行得通,但是如果我需要在组件初始化事件中更早地拥有它怎么办? this.router.url 是 '/'... :( 我需要这个来操作折叠/展开 3rd 方菜单和 NavigationEnd,即使 NavigationStart 也来不及影响菜单布局...【参考方案5】:

最简单的方法

import  Router  from '@angular/router';
constructor(router: Router)  
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  <---------- to get only path eg:"/signUp"

【讨论】:

【参考方案6】:

如果您将其与 authguard 一起使用,这适用

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

【讨论】:

【参考方案7】:

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

import ActivatedRoute from '@angular/router';

然后将其注入构造函数中

constructor(private route: ActivatedRoute)

如果您想获取当前路线,请使用此route.url

如果您有多个名称路由,例如/home/pages/list,并且您想访问个人,那么您可以访问每个这样的route.url.value[0].path

value[0] 将提供主页,value[1] 将提供页面,value[2] 将提供列表

【讨论】:

【参考方案8】:
import  Router  from '@angular/router';
constructor(router: Router)  
      console.log(router.routerState.snapshot.url);

【讨论】:

哈利路亚! :) 谢谢!【参考方案9】:

使用这个

import  Router, NavigationEnd  from '@angular/router';

constructor(private router: Router) 
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => 
            console.log(event);
        );

main.ts 导入

import 'rxjs/add/operator/filter';

编辑

现代方式

import filter from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => 
        console.log(event);
    );

【讨论】:

这真的是推荐的方法来做一些简单的事情,比如检查当前 URL 指向的位置吗?我不是在这个问题上反对你。然而,我注意到路由是许多变化、更新、混乱等的根源。我有点期待 ActivatedRoute 将主要用于此,而不是 Router .也许我错过了问题的复杂性? 这里至少不需要,路由器导出由其他路由器事件扩展的“RouterEvent”类型 - angular.io/api/router/RouterEvent @chrismarx 已修复 这很好用。但是当我启动应用程序时,第一次没有触发任何事件。这在路线改变时有效 @SunilGarg 你可以使用startsWith rxjs 运算符startWith(this.router.url),【参考方案10】:
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);
    
);

【讨论】:

【参考方案11】:
import ActivatedRoute from '@angular/router';
constructor(private route:ActivatedRoute)
    console.log(this.route.routeConfig.path);

【讨论】:

这只给出了第一段。您需要遍历 route.children[0] 并从每个段中获取 routeConfig.path 值。如果您使用辅助路由,outlet 属性会告诉您您所在的插座,您需要对此进行特殊处理。【参考方案12】:

可以在.ts文件中使用

import  Route, Router, NavigationStart  from '@angular/router';

constructor(private router: Router) 

this.router.events.subscribe(value => 
      if (value instanceof NavigationStart) 
        console.log(value) // your current route
      
    );

【讨论】:

【参考方案13】:

router.events.subscribe(e => 
      if (e instanceof NavigationEnd) 
        this.currentUrl = e.url;
      
    );

【讨论】:

【参考方案14】:

在组件文件中:

import ActivatedRouteSnapshot from '@angular/router';

constructor(state: ActivatedRouteSnapshot) 
    console.log(state.path)

在路由文件中:

【讨论】:

【参考方案15】:

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

更多,我想要一个可以在模板中使用的 Observable,所以 router.url 不是一个选项。也没有 router.events 订阅,因为路由是在组件模板初始化之前触发的。

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

希望对你有帮助,祝你好运!

【讨论】:

这太棒了。【参考方案16】:

如果你需要访问当前的 url,通常你必须等待 NavigationEnd 或 NavigationStart 来做一些事情。如果您只是订阅路由器事件,订阅将在路由生命周期中输出许多事件。相反,使用 RxJS 运算符仅过滤您需要的事件。这样做的好处是我们现在有了更严格的类型!

constructor(private router: Router) 
    router.events.pipe(
      filter(ev => (ev instanceof NavigationEnd))
    ).subscribe((ev: NavigationEnd) => 
      console.log(ev.url);
    );


【讨论】:

【参考方案17】:

原生 window 对象也可以正常工作

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

注意:不要在服务器端渲染中使用它

【讨论】:

如果你使用服务器端渲染要小心,这会中断。【参考方案18】:

方式 1:使用 Angular:this.router.url

import  Component  from '@angular/core';

// Step 1: import the router 
import  Router  from '@angular/router';

@Component(
    template: 'The href is: href'
    /*
    Other component settings
    */
)
export class Component 
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) 

    ngOnInit() 
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    

方式 2 Window.location 就像我们在 javascript 中所做的那样,如果您不想使用路由器

this.href= window.location.href;

【讨论】:

【参考方案19】:

获取路段:

import  ActivatedRoute, UrlSegment  from '@angular/router';

constructor( route: ActivatedRoute) 

getRoutes()  const segments: UrlSegment[] = this.route.snapshot.url; 

【讨论】:

【参考方案20】:

对于那些仍在寻找这个的人。在 Angular 2.x 上,有几种方法可以做到这一点。

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

【讨论】:

【参考方案21】:

Angular RC4:

您可以从@angular/router 导入Router

然后注入它:

constructor(private router: Router ) 


然后调用它的URL参数:

console.log(this.router.url); //  /routename

【讨论】:

关于如何导入路由器本身的额外说明非常有帮助。如果您使用自定义路由器,您能否澄清一下是否会有所不同? 这肯定取决于自定义路由器的“自定义性”。 (对不起,这不是一个特别有用的评论——如果你有一个具体的问题,我建议你提出一个新问题并参考这个答案) 我使用了这个解决方案,但我总是得到这个“/”。有谁知道为什么? Angular Dependency Injection 依赖于 TypeScript 糖语法,因此当您在构造函数签名中声明私有 _router:Router 时,会在当前类实例中自动创建一个属性 _router 并注入 Router。这条语句 this.router = _router;对我来说只是一个开销,因为你有两个对同一个对象实例(在这种情况下是路由器)的引用。 @Marcio M. 这可能是因为路由器实际上还没有达到那个状态,即使 URL 显示不同。例如,如果您查看保护服务中的 router.url。答案中提到的 location.path() 将为您提供 url,无论路由器状态如何。【参考方案22】:

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

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';
)

其中,routerActivatedRoute

的一个实例

【讨论】:

【参考方案23】:

如果你有 Router 导入的短版本,那么你可以简单地使用类似的东西

this.router.url === "/search"

执行以下操作

1) 导入路由器

import  Router  from '@angular/router';

2) 在构造函数中声明其入口

constructor(private router: Router)  

3) 在你的函数中使用它的值

yourFunction()
    if(this.router.url === "/search")
        //some logic
    

@victor 回答对我有帮助,这和他的回答一样,但有一点细节,因为它可能对某人有所帮助

【讨论】:

【参考方案24】:

要可靠地获得完整的当前路线,您可以使用此

this.router.events.subscribe(
  (event: any) => 
    if (event instanceof NavigationEnd) 
      console.log('this.router.url', this.router.url);
    
  
);

【讨论】:

这应该是正确的答案,因为如果你改变路线,它会抓住它。【参考方案25】:
this.router.events.subscribe((val) => 
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
);

【讨论】:

【参考方案26】:

对于新路由器 >= RC.3

最好和最简单的方法是!

import  Router  from '@angular/router';
constructor(router: Router)  
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"

【讨论】:

这个答案与 lowcrawler 的有什么不同? @not2savvy 提供了另一种通过路由器事件侦听器找出相同内容的方法,这有助于一些人找到他们正在寻找的东西。【参考方案27】:

要查找当前路由的父级,可以使用相对路由从路由器获取UrlTree

var tree:UrlTree = router.createUrlTree(['../'], relativeTo: route);

然后获取主网点的段:

tree.root.children[PRIMARY_OUTLET].segments;

【讨论】:

【参考方案28】:

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

原始答案(适用于 RC 版本)

我在AngularJS Google Group 上找到了解决方案,而且非常简单!

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

这是原来的答案

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

【讨论】:

自 rc.2 起已更改,因为 url 现在不再是 URL 和字符串,而是 ComponentInstruction【参考方案29】:

我在使用

时遇到了同样的问题
this.router.url

我使用查询参数获取当前路线。我做的一个解决方法是改用这个:

this.router.url.split('?')[0]

不是一个很好的解决方案,但很有帮助。

【讨论】:

【参考方案30】:

Location 注入您的组件并读取location.path(); 您需要在某处添加ROUTER_DIRECTIVES,以便Angular 可以解析Location您需要将import: [RouterModule] 添加到模块中。

更新

在 V3 (RC.3) 路由器中,您可以注入 ActivatedRoute 并使用其 snapshot 属性访问更多详细信息。

constructor(private route:ActivatedRoute) 
  console.log(route);

constructor(private router:Router) 
  router.events.subscribe(...);

另见Angular 2 router event listener

【讨论】:

这给了我'url'路径。我如何找到“路线名称”,以便我可以将它们与我要导航到的子路线的(附加)名称一起以数组形式传递给navigate 方法。 我明白了。我也不觉得这令人满意。我自己没有尝试过,但***.com/a/34548656/217408 中解释的MyTrackingService 可能允许访问这些值。 路线名称现已消失。 @GunterZochbauer 有没有办法让 requested 路由 before 被激活?例如,如果我想将 requested 路由存储在 canActivate() 方法中,以便我可以重定向到“登录”页面,然后将 back 重定向到用户认证后的原始路由? 你不能用 canActivate 守卫做到这一点吗?

以上是关于如何获取当前路线的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Sinatra 中获取当前路径/路线?

如何在 Symfony 2 中获取当前路线?

Mapbox Android:如何获取从当前位置到您选择的目的地的路线?

获取当前路线名称?

如何从 RouteData 获取路线名称?

Angular 2 获取当前路线