我正在尝试在路由更改时获取app.component中的当前路由名称或路由路径,以便我可以将路由名称用作包装器div周围的页面类。我正试图找出解决这个问题的最佳方法。以前我订阅了路由器更改属性,就像我在下面列出的那样,但似乎不再提供@ angular / router 3.0.0-alpha.3。如果有人有任何想法或建议,我将非常感激。
{{1}}
答案 0 :(得分:7)
ActivatedRoute
上的网址可观察到的并不是为我开除,除非我第一次点击基本网址(例如:从/ index转到/ index / item)工作,但从/ index / item到index / item / 2,index / dashboard,甚至/ index都没有)。
我不确定以下解决方案是否是最佳做法,性能影响是什么,但我能够在路由器的NavigationEnd
事件中获得活动路由,其中包含以下内容: / p>
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'navbar',
directives: [ROUTER_DIRECTIVES],
template: `
...
`
})
export class NavBarComponent implements OnInit, OnDestroy {
private sub: any;
constructor(private router: Router) {
}
ngOnInit() {
this.sub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
console.log(e.url);
}
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
无论您在网址树中的深度或导航到/从的位置,每次更改路径时都会触发此操作。
答案 1 :(得分:0)
这可能有所帮助,
import { CanActivate, Router, RouterStateSnapshot } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponent implements CanActivate {
constructor(private router: Router) {}
canActivate(state: RouterStateSnapshot) {
// this is the future route you are intended to visit
console.log(state.url);
}
}
的更多详情