2017-01-10 35 views
1

使用Angular2,我將如何檢索當前活動組件和路徑?檢索活動組件和路徑

比如我可能有以下途徑:

{ path: '', component: HomeComponent }, 
{ path: 'list', component: ListComponent }, 
{ path: ':id/', component: CustomComponent } 

如果我瀏覽到https://domain.com/test是有辦法知道我正在觀看CustomComponent和檢索ID /路徑,在此情況是「測試」?

我可以使用window.location.pathname與正則表達式來獲取路徑,但這是混亂的,仍然不允許我輕鬆獲得活動組件。

+1

您能否擴展上下文 - 您試圖用這個解決什麼問題? – jonrsharpe

+0

當然。我需要獲取用於API的路徑,但它必須在用戶正在查看'CustomComponent'時,因爲我對其他路由路徑(例如「list」)不感興趣。我只想要自定義的「ID」。 –

+1

然後你讀了文檔嗎?這在https://angular.io/docs/ts/latest/guide/router.html中有介紹 – jonrsharpe

回答

0

Yah,角度2入門指南涵蓋了所有這些,基本上你需要在你的組件上注入ActivatedRoute,然後你可以通過訂閱路由參數來獲取你想要的信息。

我真的會推薦你做英雄角度教程之旅,它實際上是他們提供的很好的學習材料。

進樣ActivatedRoute,在您的組件構造:

constructor(private route: ActivatedRoute) { 
} 

ngOnInit() { 
    this.route.params.subscribe(params => { 
     console.log(params['id']); 
    }); 
    } 
1

是的,你可以使用路由器snapshot-

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

constructor(public route : ActivatedRoute) { 
    var snapshot = route.snapshot; 
    console.log(snapshot._routeConfig.component.name); //This will give you the name of current active component 
    } 

注意 - snapshot._routeConfig.component.name它會檢查當前的活性成分給你的活動組件名稱,如果你想要的網址,你也可以通過.url而不是名稱獲得它

1

你可以enab在你的路由器配置爲根{enableTracing: true}獲得更多的想法勒跟蹤如何路由解決,激活

0

當然,使用ActivatedRoute模塊,您可以訪問路由參數或綁定到參數cgange事件

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

constructor(private activatedRoute: ActivatedRoute) { 
} 

this.activatedRoute.params.subscribe(params => { 
    console.log(params['id']); 
}); 

而且在這裏你可以也訪問您當前使用的組件類型

this.activatedRoute.component;