Files
doneit-web/src/app/services/route.service.ts
T

103 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-01-06 14:47:22 +01:00
import { Injectable } from '@angular/core';
2022-02-16 15:52:59 +01:00
import { NavigationEnd, Router, NavigationStart, NavigationExtras } from '@angular/router';
import { LocalstoreService } from '../store/localstore.service';
import { Location } from '@angular/common'
2022-01-06 14:47:22 +01:00
@Injectable({
providedIn: 'root'
})
export class RouteService {
history: any = [];
2023-10-19 15:58:55 +01:00
liveHistory = [];
2022-01-06 14:47:22 +01:00
constructor(
private router: Router,
2022-02-16 15:52:59 +01:00
private LocalstoreService: LocalstoreService,
private Location: Location
2022-01-06 14:47:22 +01:00
) {
2022-02-16 15:52:59 +01:00
this.history = this.LocalstoreService.get('history', [])
2022-01-06 14:47:22 +01:00
this.router.events.forEach((event) => {
if (event instanceof NavigationEnd) {
const lastRoute = this.history.slice(-1)
2023-10-19 15:58:55 +01:00
if (event.url != lastRoute) {
2022-01-06 14:47:22 +01:00
this.history.push(event.url)
2023-10-19 15:58:55 +01:00
this.liveHistory.push(event.url)
2022-02-16 16:21:08 +01:00
this.reduceHistory()
2022-01-06 14:47:22 +01:00
}
}
});
window['RouteService'] = this
}
/**
2022-02-16 15:52:59 +01:00
* @param url [string] incase no history to go back */
2023-10-19 15:58:55 +01:00
goBack(url = null) {
if (this.history.length >= 2) {
2022-02-16 15:49:08 +01:00
2022-01-06 14:47:22 +01:00
this.history.pop();
2022-02-16 16:21:08 +01:00
const url = this.history.pop();
2022-02-16 15:52:59 +01:00
2022-02-16 16:21:08 +01:00
this.goTo(url)
2023-10-19 15:58:55 +01:00
} else if (url) {
2022-02-16 16:21:08 +01:00
this.goTo(url)
2022-01-06 14:47:22 +01:00
}
2022-02-16 16:21:08 +01:00
this.reduceHistory()
2022-01-06 14:47:22 +01:00
}
2022-02-16 16:21:08 +01:00
goTo(url) {
let navigationExtras: NavigationExtras = {
queryParams: this.queryParams(url)
}
2023-10-19 15:58:55 +01:00
const urlObject = new URL('http://localhost:8100' + url);
2022-02-16 16:21:08 +01:00
this.router.navigate([urlObject.pathname], navigationExtras);
}
reduceHistory() {
2023-10-19 15:58:55 +01:00
if (this.history.length >= 15) {
2022-02-16 15:52:59 +01:00
this.history = this.history.slice(5, this.history.length)
}
this.LocalstoreService.set('history', this.history)
2022-01-06 14:47:22 +01:00
}
2022-02-16 16:21:08 +01:00
queryParams(url) {
2023-10-19 15:58:55 +01:00
const urlObject = new URL('http://localhost:8100' + url);
2022-02-16 16:21:08 +01:00
const paramsString = urlObject.search;
let searchParams: any = new URLSearchParams(paramsString);
let params = {}
for (let [key, value] of searchParams) {
params[key] = value
}
2023-10-19 15:58:55 +01:00
2022-02-16 16:21:08 +01:00
return params
2022-01-06 14:47:22 +01:00
}
2022-04-08 13:52:00 +01:00
getLastRoute() {
return this.history[this.history.length - 1]
}
getLastRouteA() {
return this.history[this.history.length - 2]
}
2022-01-06 14:47:22 +01:00
}