2017-04-12 23 views

回答

6

感謝大家的答案。這是我發現我必須做的。

router.events.subscribe((event: Event) => { 
    console.log(event); 
    if (event instanceof NavigationEnd) { 
    this.currentUrl = event.url; 
    } 
}); 
+0

或更短: 'router.events.subscribe(((_:NavigationEnd)=> this.currentUrl = _.url);' – ssuperczynski

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

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

雖然此代碼段可以是溶液,[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-基於代碼-答覆)確實有助於改善您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – Adam

6
找到當前路徑

最簡單的辦法是要麼你直接使用

this.router.url 

,或者你可以用它這樣的活動

上的每個路由器變更確認當前路徑
this.router.events.subscribe((res) => { 
    console.log(this.router.url,"Current URL"); 
}) 

其中router這裏例如在構造函數中創建這樣

constructor(private router: Router){ ... } 
+0

沒有進口,甚至通過構造函數獲取路由器?不起作用。 –

+0

我已經分享了通過構造函數提供路由器的代碼。顯然需要進口。反正爲什麼downvote @FeloVilches –

相關問題