ori*_*583 5 angularjs angular2-routing angular
我正在尝试在路由更改时获取app.component中的当前路由名称或路由路径,以便我可以将路由名称用作包装器div周围的页面类.我正试图找出解决这个问题的最佳方法.以前我订阅了路由器更改属性,就像我在下面列出的那样,但似乎不再提供@ angular/router 3.0.0-alpha.3.如果有人有任何想法或建议,我将非常感激.
this.router.changes.subscribe((val) => {
var path = this._location.path();
if (path.indexOf('page-name') !== -1) {
this.pageClass = 'page-name';
}
})
Run Code Online (Sandbox Code Playgroud)
史蒂夫的答案是目前记录的答案,但是ActivatedRoute当我第一次点击基本网址时,可观察到的网址并没有为我开火(例如:从/ index到/ index/item工作,但是从/ index/item到index/item/2,index/dashboard,甚至/ index不是).
我不确定以下解决方案是否是最佳实践,性能影响是什么,但我能够通过以下方式获得NavigationEnd路由器事件的活动路由:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
无论您在网址树中的深度或导航到/从的位置,每次更改路径时都会触发此操作.
这可能会有所帮助,
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);
}
}
Run Code Online (Sandbox Code Playgroud)
更多详细信息请访问https://angular.io/docs/ts/latest/guide/router.html
| 归档时间: |
|
| 查看次数: |
1936 次 |
| 最近记录: |