如何获得当前路线

pde*_*eva 394 angular2-routing angular

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

例如,如果我想找到当前路线的父母,那怎么可能呢?

Vic*_*r96 432

新的V3路由器有一个url属性.

this.router.url === '/login'
Run Code Online (Sandbox Code Playgroud)

  • 当你使用Hash策略导航时,这是无用的,url总是"/" (19认同)
  • @Murtuza 为我指明了正确的方向。但是,不需要过滤,只需监听 NavigationEnd ```this.router.events.subscribe((event) => { event instanceof NavigationEnd ? console.log(event): null })``` (5认同)
  • 我使用此代码,我在字符串变量中获取此URL但当我尝试在控制台.log中打印时,它不会打印this.fullUrl = this.router.url console.log(this.fullUrl); //不打印 (4认同)
  • @Murtuza这里是一个解决方案:`this.router.events.filter((event:any)=> event instanceof NavigationEnd).subscribe(event => {console.log('这就是您要寻找的',event.url );});`。确保从'@ angular / router'导入`import {Router,NavigationEnd};` (4认同)
  • @Murtuza 的评论/答案是正确的,只需记住现在要能够使用过滤器,您必须将其包装在管道中,这样它将是:`this.router.events.pipe(filter((event:any)=> event instanceof NavigationEnd) ).subscribe(event => { console.log('这就是您要寻找的', event.url); });` 并且您也必须导入管道。 (4认同)
  • @NinjaCoding我正在使用哈希策略,但得到的只是“ /”。如何使用Hash获取路线网址? (3认同)
  • 请查看使用新的路由器活动功能<a routerLink="/dashboard" routerLinkActive="active">信息中心</a> (2认同)
  • 这不是一个很好的解决方案,因为如果你想查看当前路由是否是根`/`,如果有一个查询字符串,你最终会得到`/?q=something`,这会破坏它。 (2认同)

low*_*ler 133

角度RC4:

您可以导入Router@angular/router

然后注入它:

constructor(private router: Router ) {

}
Run Code Online (Sandbox Code Playgroud)

然后调用它的URL参数:

console.log(this.router.url); //  /routename
Run Code Online (Sandbox Code Playgroud)

  • 我使用了这个解决方案,但我总是得到这个"/".有谁知道为什么? (31认同)
  • Angular Dependency Injection依赖于TypeScript糖语法,因此当您在构造函数签名中声明private _router:Router时,会在注入了Router的当前类实例中自动创建属性_router.这句话this.router = _router; 对我来说只是一个开销,因为你有两个引用同一个对象实例(在这种情况下,路由器). (4认同)
  • 关于如何导入路由器本身的额外清晰度非常有用.如果您使用自定义路由器,是否可以澄清它是否会有所不同? (2认同)

Gün*_*uer 52

注入Location组件并读取location.path(); 您需要添加ROUTER_DIRECTIVES某个位置以便Angular可以解析Location.您需要添加import: [RouterModule]到模块.

更新

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

constructor(private route:ActivatedRoute) {
  console.log(route);
}
Run Code Online (Sandbox Code Playgroud)

要么

constructor(private router:Router) {
  router.events.subscribe(...);
}
Run Code Online (Sandbox Code Playgroud)

另请参见Angular 2路由器事件侦听器

  • @GunterZochbauer有没有办法让_requested_ route _before_被激活?例如,如果我想将_requested_路由存储在`canActivate()`方法中,以便我可以重定向到"登录"页面,然后在用户进行身份验证后将_back_重定向到原始路由? (4认同)
  • 这给了我'url'的路径.我如何找到'路由名称',以便我可以将它们以数组形式传递给`navigate`方法以及我要导航到的子路由的(附加)名称. (3认同)

Raj*_*M S 36

对于新路由器> = 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"
}
Run Code Online (Sandbox Code Playgroud)


n4n*_*0_o 27

对于那些仍在寻找这个的人.在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
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

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


ttu*_*tes 25

获取路线段:

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

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
Run Code Online (Sandbox Code Playgroud)


Vla*_*lad 23

用这个

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

constructor(private router: Router) {
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            console.log(event);
        });
}
Run Code Online (Sandbox Code Playgroud)

并在main.ts进口

import 'rxjs/add/operator/filter';
Run Code Online (Sandbox Code Playgroud)

  • 这真的是推荐的方法吗,就像检查当前URL指向的位置一样简单吗?在这一点上,我并不反对你。但是,我注意到路由是许多更改,更新,混乱等的根源。我有点期待* ActivatedRoute *主要用于此目的,而不是* Router *。我是否想念这个问题的复杂性? (6认同)
  • 至少在这里不需要任何,路由器导出由其他路由器事件扩展的“RouterEvent”类型 - https://angular.io/api/router/RouterEvent (2认同)

Cha*_*har 17

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*nam 12

你可以试试

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) }
Run Code Online (Sandbox Code Playgroud)

替代方式

router.location.path();   this works only in browser console. 
Run Code Online (Sandbox Code Playgroud)

window.location.pathname 它给出了路径名称.


And*_*scu 12

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

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);
Run Code Online (Sandbox Code Playgroud)


San*_*rde 9

本机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);
Run Code Online (Sandbox Code Playgroud)

注意:请勿在服务器端部渲染中使用它

  • 如果您使用服务器端渲染,请小心,这会破坏。 (3认同)

Ant*_* T. 7

我在使用时遇到了同样的问题

this.router.url
Run Code Online (Sandbox Code Playgroud)

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

this.router.url.split('?')[0]
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*een 6

简短的版本,如果您导入了路由器,那么您可以简单地使用诸如

this.router.url ===“ /搜索”

否则请执行以下操作

1)导入路由器

import { Router } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

2)在构造函数中声明其条目

constructor(private router: Router) { }
Run Code Online (Sandbox Code Playgroud)

3)在您的函数中使用其值

yourFunction(){
    if(this.router.url === "/search"){
        //some logic
    }
}
Run Code Online (Sandbox Code Playgroud)

@victor的答案对我有所帮助,这与他的答案相同,但有一点细节,因为它可能对某人有帮助


Tri*_*hak 6

方式 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

this.href= window.location.href;
Run Code Online (Sandbox Code Playgroud)


abu*_*hir 6

要在 angular 8 中获取当前路由器,只需执行此操作

import {ActivatedRoute} from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

然后将其注入构造函数中

constructor(private route: ActivatedRoute){}
Run Code Online (Sandbox Code Playgroud)

如果你想获得当前路线然后使用这个 route.url

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

value[0]会给家,value[1]会给你页面,value[2]会给你列表


Yoh*_*ani 6

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

constructor(private readonly location: Location) {}

ngOnInit(): void {
  console.log(this.location.path());
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*nyo 6

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

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );
Run Code Online (Sandbox Code Playgroud)


Arp*_*wal 5

在Angular2 Rc1中,您可以注入RouteSegment并以naviagte方法传递它们.

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

  ngOnInit() {
    this.router.navigate(["explore"],this.segment)
  }
Run Code Online (Sandbox Code Playgroud)


adr*_*rhc 5

使用angular 2.2.1(在基于angular2-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();
  }
}
Run Code Online (Sandbox Code Playgroud)

在AppComponent的模板中,您可以使用{{activeUrl}}。

该解决方案的灵感来自RouterLinkActive的代码。


And*_*scu 5

我遇到的问题是,当用户浏览应用程序访问 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)
);
Run Code Online (Sandbox Code Playgroud)

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

  • 这太棒了。 (2认同)

小智 5

您可以在 .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
      }
    });
Run Code Online (Sandbox Code Playgroud)


Ham*_*mza 5

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);
    }
});
Run Code Online (Sandbox Code Playgroud)


Nae*_*hir 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"
}
Run Code Online (Sandbox Code Playgroud)