角度 2 路由事件

Angular2 Route events

本文关键字:事件 路由 角度      更新时间:2023-09-26

我正在使用 Angular2 路由,我需要在路由更改时订阅事件。(即用户单击了其中一个路由链接)。重要的是,该事件应该是将新视图 HTML 插入到 DOM 时。

是否有任何事件,如 onNavigating 和 onNavigated,以便我可以订阅?我在stackoverflow上找到了几个示例并尝试使用它们(请参阅下面的构造函数),但这不起作用。有什么想法吗?

/// <reference path="../../typings/tsd.d.ts" />
import {Component, View} from 'angular2/angular2';
import {RouteConfig, Router, RouterOutlet, RouterLink} from 'angular2/router';
@RouteConfig([...])
@Component({
selector: 'app'
})
@View({
directives: [RouterOutlet, RouterLink],
template: `
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
  <div class="mdl-layout__header-row">
    <span class="mdl-layout-title">Test</span>
    <div class="mdl-layout-spacer"></div>
    <nav class="mdl-navigation mdl-layout--large-screen-only">
      <a class="mdl-navigation__link" [router-link]="['/routelink1']">routelink1</a>
    </nav>
  </div>
</header>
<main class="mdl-layout__content" style="padding: 20px;">
  <router-outlet></router-outlet>
</main>
</div>
`
})
export class App {
constructor(private router: Router){
      router.subscribe((val) => function(){...}); //here is I need to process HTML
   }
}

我最终为我的路由组件提供了基类,它包含routerOnNaving覆盖。

import {OnActivate, ComponentInstruction} from 'angular2/router';
export class BaseView implements OnActivate {
  routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
     componentHandler.upgradeDom();
  }
}