Created
June 24, 2022 16:50
-
-
Save CliffCrerar/22189fe9396e5c27d4876470e43585e0 to your computer and use it in GitHub Desktop.
Angular URL tracking service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from '@angular/core'; | |
import {NavigationEnd, Router, RouterEvent} from "@angular/router"; | |
import {filter} from "rxjs/operators"; | |
import {Subscription} from "rxjs"; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class TrackUrlHistoryService { | |
/* PROPERTIES */ | |
private _router: Router; | |
private _store: Storage; | |
private readonly _storeKey: string; | |
private _routeEventSubscription: Subscription; | |
private _urlHistoryCount: number = 10; | |
/* CONSTRUCTOR */ | |
constructor () { | |
this._router = {} as any; | |
this._store = sessionStorage; | |
this._storeKey = 'url-history'; | |
this._routeEventSubscription = new Subscription(); | |
} | |
/* GETTER SETTER */ | |
set router (value: Router) { | |
this._store.setItem(this._storeKey, '[]'); | |
this._router = value; | |
this._startTrackingRoutes(); | |
} | |
set urlHistoryCount (value: number) { | |
this._urlHistoryCount = value; | |
} | |
get urlHistory (): string[] { | |
return JSON.parse(this._store.getItem('url-history') as string) as string[]; | |
} | |
set urlHistory (newUrl: string[]) { | |
console.log(newUrl); | |
console.log(location.pathname) | |
const thisPath = newUrl[ 0 ]; | |
const history = this.urlHistory; | |
if (history[ 0 ] == thisPath) return; | |
const existingPathIndex = this.urlHistory.indexOf(thisPath); | |
console.log(existingPathIndex); | |
if (existingPathIndex > -1) { | |
history.splice(existingPathIndex, 1); | |
console.log(this.urlHistory); | |
} | |
const urlHistory = [thisPath, ...history]; | |
if (urlHistory.length > this._urlHistoryCount) { | |
urlHistory.pop(); | |
} | |
sessionStorage.setItem('url-history', JSON.stringify(urlHistory)); | |
} | |
/* METHODS */ | |
private _startTrackingRoutes () { | |
this._routeEventSubscription = this._router.events | |
.pipe(filter(routeEvent => routeEvent instanceof NavigationEnd)) | |
.subscribe((routeEvent: any) => { | |
this.urlHistory = [routeEvent.urlAfterRedirects] | |
}) | |
} | |
public unsubscribeRouteTracker () { | |
this._routeEventSubscription.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment