跟踪 Angular2 当前路线

Track Angular2 Current Route

在我的 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 但那只是 returns SeedApp。

我也尝试过使用 routerOnActivate 函数来获取我们正在导航到的那个,但这从来没有被调用过。

1) 您可以订阅路由器,并且可以知道您的路由器路由到的当前路由。在父组件或包含 route.config 这样的组件中,

export class SeedApp implements OnActivate {
 constructor(router:Router)
  {
       this.router=router;
       this.router.subscribe((nextValue) => {
            console.log(nextValue);
       });
   ...    
  }
..
}


2) 通过使用 CanActive 挂钩达到特定的 route/component 级别,

import {CanActivate,OnActivate} from 'angular2/router';

@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
  console.log(next);
  return true;
})
export class About {
}