编程语言
首页 > 编程语言> > javascript – Angular 2路由器事件监听器

javascript – Angular 2路由器事件监听器

作者:互联网

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

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

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

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

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()在服务中不起作用.

我做错了什么?

解决方法:

新的路由器

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

注意

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

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

因为如果你不导入它,instanceof将无法工作,并且未定义错误NavigationStart将会上升.

也可以看看

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

标签:javascript,angular,typescript,angular2-routing
来源: https://codeday.me/bug/20190916/1807267.html