Angular 2,从不为实现OnActivate

时间:2016-01-09 23:21:33

标签: angular angular2-routing

我正在尝试使用Angular 2路由器记录当前路由,使用官方文档中的示例代码:https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html

import {Component} from 'angular2/core';
import {
    OnActivate,
    ComponentInstruction
} from 'angular2/router';


@Component({selector: 'header-title', template: `<div>routerOnActivate: {{log}}</div>`})
export class HeaderTitle implements OnActivate {
    log: string = '';

    routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
        console.log('hello on activate');
        this.log = `Finished navigating from "${prev ? prev.urlPath : 'null'}" to "${next.urlPath}"`;
    }
}

永远不会调用方法routerOnActivate

我使用RouteConfig注释配置路线:

@RouteConfig([
    {path: '/', component: Home, name: 'Index', data: {title: 'Index page'}},
    {path: '/home', component: Home, name: 'Home', data: {title: 'Welcome Home'}},
    {path: '/**', redirectTo: ['Index']}
])

我还应该在路由器中配置其他东西以激活侦听器吗?

1 个答案:

答案 0 :(得分:12)

您需要在解析路径的组件中实现routerOnActivate方法。在您的示例中,如果您在Home Component中实现它,则会调用它。