2021-07-06 11:23:49 +02:00
|
|
|
import { Injectable, OnDestroy } from "@angular/core";
|
|
|
|
import { CanActivate, NavigationEnd, NavigationStart, Router } from "@angular/router";
|
|
|
|
import { Subscription } from "rxjs";
|
|
|
|
import { filter, pairwise } from "rxjs/operators";
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class DebounceNavigationService implements CanActivate, OnDestroy {
|
|
|
|
navigationStartSub: Subscription;
|
|
|
|
navigationSuccessSub: Subscription;
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-07-06 11:23:49 +02:00
|
|
|
private lastNavigation: NavigationStart;
|
|
|
|
private thisNavigation: NavigationStart;
|
|
|
|
private lastNavigationSuccessId: number;
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-07-06 11:23:49 +02:00
|
|
|
constructor(private router: Router) {
|
|
|
|
this.navigationStartSub = this.router.events
|
|
|
|
.pipe(
|
|
|
|
filter((event) => event instanceof NavigationStart),
|
|
|
|
pairwise()
|
2021-12-21 15:43:35 +01:00
|
|
|
)
|
2021-07-06 11:23:49 +02:00
|
|
|
.subscribe(
|
|
|
|
(events: [NavigationStart, NavigationStart]) =>
|
|
|
|
([this.lastNavigation, this.thisNavigation] = events)
|
|
|
|
);
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-07-06 11:23:49 +02:00
|
|
|
this.navigationSuccessSub = this.router.events
|
|
|
|
.pipe(filter((event) => event instanceof NavigationEnd))
|
|
|
|
.subscribe((event: NavigationEnd) => (this.lastNavigationSuccessId = event.id));
|
2021-12-21 15:43:35 +01:00
|
|
|
}
|
|
|
|
|
2021-07-06 11:23:49 +02:00
|
|
|
async canActivate() {
|
2021-12-21 15:43:35 +01:00
|
|
|
return !(
|
2021-07-06 11:23:49 +02:00
|
|
|
this.thisNavigation?.navigationTrigger === "hashchange" &&
|
|
|
|
this.lastNavigation.navigationTrigger === "popstate" &&
|
|
|
|
this.lastNavigationSuccessId === this.lastNavigation.id &&
|
|
|
|
this.lastNavigation.url === this.thisNavigation?.url
|
2021-12-21 15:43:35 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-07-06 11:23:49 +02:00
|
|
|
ngOnDestroy() {
|
|
|
|
if (this.navigationStartSub != null) {
|
|
|
|
this.navigationStartSub.unsubscribe();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.navigationSuccessSub != null) {
|
|
|
|
this.navigationSuccessSub.unsubscribe();
|
|
|
|
}
|
2021-12-21 15:43:35 +01:00
|
|
|
}
|
2021-07-06 11:23:49 +02:00
|
|
|
}
|