目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
当我想要根据路线改变背景时,我面临着这个问题。但它只在我浏览网站时工作,而不是当我刷新页面时。
在router.events.subscribe()中,这是事件。导航时的Url,刷新时的this。router。Url。
现在它起作用了:
import { ActivatedRoute, Router, NavigationStart } from '@angular/router';
constructor(private router: Router) {}
public ngOnInit() {
this.router.events.subscribe((events:any) => {
let theme = '';
if (events instanceof NavigationStart) { theme = events.url; }
else { theme = this.router.url; }
if(theme === '/videos') { ... }
}
其他回答
给那些还在寻找这个的人。在Angular 2上。有几种方法。
constructor(private router: Router, private activatedRoute: ActivatedRoute){
// string path from root to current route. i.e /Root/CurrentRoute
router.url
// just the fragment of the current route. i.e. CurrentRoute
activatedRoute.url.value[0].path
// same as above with urlSegment[]
activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))
// same as above
activatedRoute.snapshot.url[0].path
// the url fragment from the parent route i.e. Root
// since the parent is an ActivatedRoute object, you can get the same using
activatedRoute.parent.url.value[0].path
}
引用:
https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html https://angular.io/docs/ts/latest/api/router/index/Router-class.html https://angular.io/docs/ts/latest/guide/router.html
Angular 2 rc2
router.urlTree.contains(router.createUrlTree(['/home']))
新建路由器>= 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"
}
这适用于与authguard一起使用的情况
this.router.events.subscribe(event => {
if(event instanceof NavigationStart){
console.log('this is what your looking for ', event.url);
}
}
);
import { Router, NavigationEnd } from "@angular/router";
constructor(private router: Router) {
// Detect current route
router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
console.log(val.url);
}
});
}