我正在尋找一種獲取當前路線路徑名的好方法。這是我能找到的最簡單的方法。在Angular 4中獲取當前路徑路徑名的最簡單方法是什麼?
this.route.snapshot.firstChild.url[0].path
有沒有更好的辦法?謝謝!
我正在尋找一種獲取當前路線路徑名的好方法。這是我能找到的最簡單的方法。在Angular 4中獲取當前路徑路徑名的最簡單方法是什麼?
this.route.snapshot.firstChild.url[0].path
有沒有更好的辦法?謝謝!
感謝大家的答案。這是我發現我必須做的。
router.events.subscribe((event: Event) => {
console.log(event);
if (event instanceof NavigationEnd) {
this.currentUrl = event.url;
}
});
constructor(private route:ActivatedRoute) {
console.log(route);
}
或
constructor(private router:Router) {
router.events.subscribe(...);
}
雖然此代碼段可以是溶液,[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-基於代碼-答覆)確實有助於改善您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – Adam
最簡單的辦法是要麼你直接使用
this.router.url
,或者你可以用它這樣的活動
上的每個路由器變更確認當前路徑this.router.events.subscribe((res) => {
console.log(this.router.url,"Current URL");
})
其中router
這裏例如在構造函數中創建這樣
constructor(private router: Router){ ... }
沒有進口,甚至通過構造函數獲取路由器?不起作用。 –
我已經分享了通過構造函數提供路由器的代碼。顯然需要進口。反正爲什麼downvote @FeloVilches –
或更短: 'router.events.subscribe(((_:NavigationEnd)=> this.currentUrl = _.url);' – ssuperczynski