Angular 2路由器事件监听器 [英] Angular 2 router event listener

查看:397
本文介绍了Angular 2路由器事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular 2路由器中监听状态更改?

How to listen state change in Angular 2 router?

在Angular 1.x中我使用了此事件:

In Angular 1.x I used this event:

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

所以,如果我在Angular 2中使用这个eventlistener:

So, if I use this eventlistener in Angular 2:

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

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

it isn't return 'ok', then change state from JS, only then browser history.back() function run.

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

Use router.subscribe() function as the service:

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');
        })
    }
}

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

Inject service in component which init in routing:

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()服务不工作。

I inject this service in other components such as in this example. Then I change state, console.info() in service not working.

我做错了什么?

推荐答案

新路由器

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

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

Inject the Router and subscribe to route change events

import {Router} from 'angular2/router';

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

注意

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

For the new router, don't forget to import NavigationStart from router module

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

因为如果你不导入它 instanceof 将无效并且错误 NavigationStart未定义将上升。

because if you don't import it instanceof will not work and an error NavigationStart is not defined will rise.

参见

  • https://angular.io/docs/ts/latest/api/router/index/Router-class.html
  • How to detect a route change in Angular 2?

这篇关于Angular 2路由器事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆