feat(common): add ability to track all location changes (#30055)

This feature adds an `onUrlChange` to Angular's `Location` class. This is useful to track all updates coming from anywhere in the framework. Without this method, it's difficult (or impossible) to track updates run through `location.go()` or `location.replaceState()` as the browser doesn't publish events when `history.pushState()` or `.replaceState()` are run.

PR Close #30055
This commit is contained in:
Jason Aden
2019-04-22 15:48:27 -07:00
committed by Ben Lesh
parent 152d99eef0
commit 3a9cf3f2ba
3 changed files with 65 additions and 2 deletions

View File

@ -57,6 +57,7 @@ export class Location {
_platformStrategy: LocationStrategy;
/** @internal */
_platformLocation: PlatformLocation;
private urlChangeListeners: any[] = [];
constructor(platformStrategy: LocationStrategy, platformLocation: PlatformLocation) {
this._platformStrategy = platformStrategy;
@ -146,6 +147,8 @@ export class Location {
*/
go(path: string, query: string = '', state: any = null): void {
this._platformStrategy.pushState(state, '', path, query);
this.notifyUrlChangeListeners(
this.prepareExternalUrl(path + Location.normalizeQueryParams(query)), state);
}
/**
@ -158,6 +161,8 @@ export class Location {
*/
replaceState(path: string, query: string = '', state: any = null): void {
this._platformStrategy.replaceState(state, '', path, query);
this.notifyUrlChangeListeners(
this.prepareExternalUrl(path + Location.normalizeQueryParams(query)), state);
}
/**
@ -170,6 +175,20 @@ export class Location {
*/
back(): void { this._platformStrategy.back(); }
/**
* Register URL change listeners. This API can be used to catch updates performed by the Angular
* framework. These are not detectible through "popstate" or "hashchange" events.
*/
onUrlChange(fn: (url: string, state: unknown) => void) {
this.urlChangeListeners.push(fn);
this.subscribe(v => { this.notifyUrlChangeListeners(v.url, v.state); });
}
private notifyUrlChangeListeners(url: string = '', state: unknown) {
this.urlChangeListeners.forEach(fn => fn(url, state));
}
/**
* Subscribe to the platform's `popState` events.
*