【发布时间】:2016-01-09 23:21:33
【问题描述】:
我正在尝试使用 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']}
])
我应该在路由器中配置其他什么来激活侦听器吗?
【问题讨论】:
-
implement部分在这里并不重要。HeaderTitle是通过路由加载的吗?否则它不会工作。 -
@EricMartinez 你的意思是我应该把它加载到像 Home 组件
{path: '/', component: Home, name: 'Index', data: {title: 'Index page'}}这样的路由中?它当前是通过 Home 组件模板中包含的指令<header-title></header-title>加载的。 -
是的,完全是@gpereira。
implement部分仅用于帮助您进行打字,因此 IDE 不会抱怨。确保在您的Home组件中添加一个routerOnActivaite并查看它是否被调用。