Angular 2,永远不会为实现 OnActivate 的组件调用 routerOnActivate 方法

标签 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']}
])

我应该在路由器中配置其他东西来激活监听器吗?

最佳答案

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

关于Angular 2,永远不会为实现 OnActivate 的组件调用 routerOnActivate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700108/

相关文章:

javascript - 如何执行某些功能

angular - 如何创建一个仅在订阅时每 10 秒(间隔)更新其值的 Observable?

javascript - 如何提高 Angular2 应用程序的加载性能?

Angular2 Router v3,导航到不同的级别 : TypeError: Cannot read property '_routeConfig' of null

angular - 如何以 Angular 方式获取 Angular2 路由上的参数?

angular - 使用 angular 4 登录表单通过 IdentityServer 4 对应用程序进行身份验证

excel - 在 Angular 8 应用程序中导出 Excel 文件时如何定义单元格文本对齐方式?

javascript - Angular 2 routerLink 无法在路由器导出内工作

angular - Firefox/Chrome 未在 2000 毫秒内被杀死,发送 SIGKILL

angular 2 服务订阅仅在第二次单击带有 routerLink(s) 的组件后更新