2016-01-04 65 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); 
相關問題