2016-01-04 66 views
140

当前文档仅讨论获取路线参数,而不是实际路线段。如何获取当前路线

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

+3

'window.location.pathname' – weltschmerz

回答

35

进样Location到您的组件和阅读location.path(); 您需要添加 ROUTER_DIRECTIVES这样的地方能角度解决 Location您需要将import: [RouterModule]添加到模块中。

更新

在你可以注入ActivatedRoute并访问使用其snapshot属性的细节的V3(RC.3)路由器。

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

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

Angular 2 router event listener

+2

,让我 '网址' 路径。我如何找到“路由名称”,以便我可以将它们传递到'navigate'方法以及要导航到的子路由的(附加)名称。 – pdeva

+0

我明白了。我也不觉得满意。我没有自己尝试过,但也许http://stackoverflow.com/a/34548656/217408中解释的“MyTrackingService”允许访问这些值。 –

+0

路由名称现在消失了。 –

4

看到在Angular2器Rc1你可以注入RouteSegment,并通过他们在naviagte方法。

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

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

角2 RC2

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

新V3路由器具有url属性。

this.router.url === '/login' 
+3

我使用此代码和我在字符串变量中获取此URL,但是当我尝试在控制台.log中打印时,它不打印this.fullUrl = this.router.url console.log(this.fullUrl); //不打印 –

+0

看看使用新的路由器主动功能Dashboard Victor96

+0

这与当前的[angular2-seed](https://github.com/angular/angular2-seed)(它目前在角2.2.1) 。 –

46

角RC4:

您可以从@angular/router

导入Router然后把它注射:

constructor(private _router: Router) { 
    this.router = _router; 
} 

然后调用它的URL参数:

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

关于如何导入路由器本身的额外清晰度非常有帮助。你能澄清一下,如果你使用自定义的路由器会不同吗? – kbpontius

+1

这肯定取决于自定义路由器的'自定义'。 (对不起,这不是一个特别有用的评论 - 如果你有一个具体的问题,我会建议提出一个新的问题,并参考这个答案) – lowcrawler

+5

我用这个解决方案,但我总是得到这个“/”。有谁知道为什么? –

7

您可以

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) } 

替代方式

router.location.path(); this works only in browser console. 

window.location.pathname这给路径名试试。

+0

更新:activatedRoute.snapshot.url现在是一个Observable,你必须使用它。 –

3

正确答案今天将是:

1)进口ActivatedRoute:

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

2)创建你的类属性来存储网址:

private myUrl:any; 

3)创建从ActivatedRoute构造函数中的实例,并得到你想要的一切:

constructor (...private route:ActivatedRoute, ...) { 
    this.route.url.subscribe(
    (data: any) => { 
     for (let i of data) { 
      this.myUrl = i.path; 
      // ... get whatever you want 
     } 
     console.log("My Current Url ", this.myUrl); 
     console.log("There is something more: ",data); 
    }, 
    (error: any) => console.debug("URL ERROR", error)); 
} 
1

为了您的目的,您可以使用this.activatedRoute.pathFromRoot

import {ActivatedRoute} from "@angular/router"; 
constructor(public activatedRoute: ActivatedRoute){ 

} 

随着pathFromRoot的帮助下,你可以得到父母的URL列表,并检查URL的一部分所需的条件相匹配。

有关更多信息,请查看这篇文章http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ 或NPM

npm install ng2-router-helper 
30

安装NG2路由器辅助新路由器> = 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" 
} 
+0

此答案与lowcrawler不同? – not2savvy

+0

@ not2savvy通过路由器事件监听器给出了另外一种方法来找出相同的方法,这有助于一些人找到他们正在寻找的东西。 –

0

这可能是你的答案,激活航线的使用PARAMS方法从URL /路由,你想读的参数,则下面是演示片断

import {ActivatedRoute} from '@angular/router'; 
@Component({ 
}) 
export class Test{ 
constructor(private route: ActivatedRoute){ 
this.route.params.subscribe(params => { 
      this.yourVariable = params['required_param_name']; 
     }); 
    } 
} 
+0

欢迎来到Stack Overflow!尽管这段代码可以解决这个问题,但[包括一个解释](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高您的帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性注释来挤占代码,这会降低代码和解释的可读性! – kayess

3

随着角度2.2.1(以一个angular2-的WebPack起动基于项目)的工作原理是:

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

11

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

constructor(private router: Router, private activatedRoute: ActivatedRoute){ 
    router.url //Gives you the string path from root to current route. i.e /Root/CurrentRoute 
    activatedRoute.url.value[0].path //Gives you just the fragment of the current route. i.e. CurrentRoute 
    activatedRoute.url.subscribe((url: urlSegment)=> console.log(url[0].path)) //The same as above 
    activatedRoute.snapshot.url[0].path //Save as above 

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

参考文献:

  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
+0

做得很好。只需更新一下: _router.url; _activatedRoute.url ['value'] [0] .path; _activatedRoute.url.subscribe((url:UrlSegment [])=> console.log(url [0] .path)); _activatedRoute.snapshot.url [0] .path; _activatedRoute.parent.url ['value'] [0] .path; – BBaysinger

2

这里是在角2.3.1为我工作。

location: any; 

constructor(private _router: Router) { 

     _router.events.subscribe((data:any) => { this.location = data.url; }); 

     console.warn(this.location); // This should print only path e.g. "/home" 
} 

data是一个对象,我们需要包含在该对象的url属性。所以我们在变量中捕获这个值,我们也可以在HTML页面中使用这个变量。例如,我只想在用户在主页上时显示一个div。在这种情况下,我的路由器url值将是/home。所以,我可以写在下面的方式一个div:

<div *ngIf="location == '/home'"> 
This is content for the home page. 
</div> 
1

这很简单,在角2你只需要导入路由器库这样的:

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

然后在构造函数该组件或服务必须将它实例是这样的:在代码中的任何部分

constructor(private _router: Router) {} 

然后,无论是在功能,方法,构造,无论:

 this._router.events 
     .subscribe(
      (url:any) => { 
       let _ruta = ""; 
       url.url.split("/").forEach(element => { 
        if(element!=="" && _ruta==="") 
         _ruta="/"+element; 
       }); 
       console.log("route: "+_ruta); //<<<---- Root path 
       console.log("to URL:"+url.url); //<<<---- Destination URL      
       console.log("from URL:"+this._router.url);//<<<---- Current URL 
      }); 
1

我不得不使用

this.router.url 

我与查询参数当前路由同样的问题。我采取的解决方法是使用此代替:

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

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

16

在Angular 4/5中获取路线段。

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

constructor(route: ActivatedRoute) {} 

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

要查找当前路线的父母,你可以从路由器UrlTree,使用相对路径:

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

然后拿到第一出口的部分:

tree.root.children[PRIMARY_OUTLET].segments; 
4

使用此

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

而且在main.ts进口

import 'rxjs/add/operator/filter'; 
1

天然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); 
相关问题