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

2023-12-26

我正在尝试使用 Angular 2 Router 记录当前路由,使用官方文档中的示例代码:https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html 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 组件中实现它,它将被调用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2,实现 OnActivate 的组件永远不会调用 routerOnActivate 方法 的相关文章