Егор Медведев Егор Медведев - 5 months ago 1448
AngularJS Question

Angular 2 router event listener

How to listen state change in Angular 2 router?

In Angular 1.x I used this event:

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


So, if I use this eventlistener in Angular 2:

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


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

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) {}
}


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

What I do wrong?

Answer

new router

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

original

Inject the Router and subscribe to route change events

import {Router} from 'angular2/router';

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