Angular 2 路由器事件监听器

新手上路,请多包涵

如何监听 Angular 2 路由器中的状态变化?

在 Angular 1.x 中,我使用了这个事件:

 $rootScope.$on('$stateChangeStart',
    function(event,toState,toParams,fromState,fromParams, options){ ... })

所以,如果我在 Angular 2 中使用这个事件监听器:

 window.addEventListener("hashchange", () => {return console.log('ok')}, false);

它不返回“ok”,然后从 JS 更改状态,然后浏览器 history.back() 函数运行。

使用 router.subscribe() 函数作为服务:

 import {Injectable} from 'angular2/core';
import {Router} from 'angular2/router';

@Injectable()
export class SubscribeService {
    constructor (private _router: Router) {
        this._router.subscribe(val => {
            console.info(val, '<-- subscribe func');
        })
    }
}

在路由中初始化的组件中注入服务:

 import {Component} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    selector: 'main',
    templateUrl: '../templates/main.html',
    providers: [SubscribeService]
})
export class MainComponent {
    constructor (private subscribeService: SubscribeService) {}
}

我将此服务注入到其他组件中,例如在本示例中。然后我更改状态,服务中的 console.info() 不起作用。

我做错了什么?

原文由 Yegor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 505
2 个回答

新路由器

constructor(router:Router) {
  router.events.subscribe(event:Event => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

老的

注入路由器并订阅路由更改事件

import {Router} from 'angular2/router';

class MyComponent {
  constructor(router:Router) {
    router.subscribe(...)
  }
}

笔记

对于新路由器,不要忘记从 router 模块导入 NavigationStart

 import { Router, NavigationStart } from '@angular/router';

因为如果您不导入它 instanceof 将不起作用并且错误 NavigationStart is not defined 会上升。

也可以看看

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

直接来自 文档

import {Event, RouterEvent, Router, NavigationEnd} from '@angular/router';

this.router.events.pipe(
  filter((e: any): e is RouterEvent => e instanceof RouterEvent)
).subscribe((evt: RouterEvent) => {
  if (evt instanceof NavigationEnd) {
    console.log(evt.url)
  }
})

尽管文档给出了代码 filter((e: Event) 但我将其更改为 filter((e: any) 否则您会在 WebStorm 中遇到 linting 错误。

原文由 danday74 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题