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

查看:30
本文介绍了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 中使用这个事件监听器:

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(...)
  }
}

注意

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

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

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

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

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

另见

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

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