【问题标题】:Angular 2, routerOnActivate method is never called for a component that implements OnActivateAngular 2,永远不会为实现 OnActivate 的组件调用 routerOnActivate 方法
【发布时间】: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 组件模板中包含的指令 &lt;header-title&gt;&lt;/header-title&gt; 加载的。
  • 是的,完全是@gpereira。 implement 部分仅用于帮助您进行打字,因此 IDE 不会抱怨。确保在您的 Home 组件中添加一个 routerOnActivaite 并查看它是否被调用。

标签: angular angular2-routing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2017-12-18
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多