Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  118] [ 4]  / answers: 1 / hits: 123594  / 8 Years ago, thu, march 10, 2016, 12:00:00

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?


More From » angular

 Answers
25

new router



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


old



Inject the Router and subscribe to route change events



import {Router} from 'angular2/router';

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


NOTE



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



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


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



See also




[#62991] Monday, March 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;