Using Angular 2, I have a component that subscribes to a service based on the URL hash. No subcomponents are called by the URL change. I assume this would require Route, though Location might be more appropriate. How do I listen and react to a pop state event?
Asked
Active
Viewed 4,364 times
1 Answers
2
If you wish to listen to route changes you can use the Router.
import {Location} from '@angular/common';
import {Router} from '@angular/router'
export class SomeComponent {
constructor(router:Router, private location:Location) {
router.changes.subscribe(() => this.routeChanged());
}
private routeChanged():void {
var path:string = this.location.path();
console.log("Path:" + path);
}
}
Is this what you wish to do?

Sebastian
- 159
- 6
-
1Where did you find Router.changes()? It's not listed in the [Router documentation](https://angular.io/docs/js/latest/api/router/Router-class.html) – ebakunin May 13 '16 at 01:13
-
https://github.com/angular/angular/blob/b30ddfbfc5192f526ceaac525cf6965635831c46/modules/%40angular/router/src/router.ts#L74. https://angular.io/docs/ts/latest/api/router/index/Router-interface.html also shows "`changes : Observable
` An observable or url changes from the router." – Günter Zöchbauer May 13 '16 at 04:22 -
@GünterZöchbauer when I run the above code I get an error. Is the code crafted correctly? I am running version 2.0.0-beta.9. `TypeError: router.changes is undefined` – ebakunin May 13 '16 at 05:15
-
the given example is angular2-rc1 before it was like `router.subscribe(results => this.routeChanged(results)); private routeChanged(path:string):void { console.log("New Route:" + path); } ` You were able to get the currunt route from method-parameters, since angular2-rc0 i think it changed and u only get a void method-header. so i was injecting Location – Sebastian May 13 '16 at 13:22
-
@Sebastian switching to only using `router.subscribe()` throws `TypeError: instruction is null`. Perhaps a better way of approaching this problem is explaining how to add instructions to Route. Can you recommend an up-to-date tutorial? – ebakunin May 13 '16 at 19:22
-
i created a plunker with angular version 2.0.0-beta.9 example of router and subscribing to the route change event. http://plnkr.co/edit/veSOXF0rJyU6hYkqKtJW?p=preview i hope this can help you. if this is not waht you want i cant answer your question :( – Sebastian May 14 '16 at 01:06
-
Looks like the code is outdated. I've added a currently valid solution with Angular4: http://jsfiddle.net/85yhu618/ If you need the real url, import Router and use this.router.routerState.snapshot.url); – netzaffin Aug 10 '17 at 15:48