在我的angular2应用程序中,我有一个shell组件,其中包含一些通过路由加载的子组件。
import {Component} from 'angular2/core';
import {Router, Route, RouteConfig, Location, ROUTER_DIRECTIVES, OnActivate, ComponentInstruction} from 'angular2/router';
import {Home} from './components/home/home';
import {About} from './components/about/about';
import {RepoBrowser} from './components/repo-browser/repo-browser';
@Component({
selector: 'seed-app',
providers: [],
templateUrl: 'app/seed-app.html',
directives: [ROUTER_DIRECTIVES],
pipes: []
})
@RouteConfig([
new Route({ path: '/home', component: Home, name: 'Home', useAsDefault: true }),
new Route({ path: '/about', component: About, name: 'About' }),
new Route({ path: '/github/...', component: RepoBrowser, name: 'RepoBrowser' })
])
export class SeedApp implements OnActivate {
route: string;
constructor(public router: Router) {
this.route = this.router.hostComponent.name;
}
routerOnActivate(next: ComponentInstruction, prev:ComponentInstruction) {
console.log('hi');
this.route = next.urlPath;
}
}
我要做的是在此组件级别跟踪当前选定的路线。正如您在我的构造函数中看到的那样,我尝试获取this.router.hostComponent.name
,但这只是返回SeedApp。
我还尝试使用routerOnActivate函数来获取我们正在导航的那个,但这永远不会被调用。
答案 0 :(得分:1)
1)您可以订阅路由器,并且可以知道您的路由器路由到的当前路由。在父组件或包含route.config
的组件中,
export class SeedApp implements OnActivate {
constructor(router:Router)
{
this.router=router;
this.router.subscribe((nextValue) => {
console.log(nextValue);
});
...
}
..
}
<小时/> 2)使用
CanActive
这样的挂钩,到特定的路由/组件级别
import {CanActivate,OnActivate} from 'angular2/router';
@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
console.log(next);
return true;
})
export class About {
}