import { Injectable } from '@angular/core';
import {
ActivatedRoute,
NavigationCancel,
NavigationEnd,
NavigationError,
NavigationStart,
Router,
} from '@angular/router';
import { BehaviorSubject, Observable, filter, map } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class RoutingStatus {
private routingInProgress = new BehaviorSubject<boolean>(false);
private routingInProgress$ = this.routingInProgress.asObservable();
// create private variable for subscriptions;
// create decorator to unsubscribe subscriptions
constructor(
private route: ActivatedRoute,
private router: Router,
) {
this.listenRouterLoadingStatus();
}
getRouterLoadingStatus(): Observable<boolean> {
return this.routingInProgress$;
}
setRouterLoadingStatus(latestValue: boolean) {
return this.routingInProgress.next(latestValue);
}
listenRouterLoadingStatus(): void {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.setRouterLoadingStatus(true);
}
if (event instanceof NavigationEnd) {
this.setRouterLoadingStatus(false);
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this.setRouterLoadingStatus(false);
}
if (event instanceof NavigationError) {
this.setRouterLoadingStatus(false);
}
});
}
// Get Current / Active Router Config
getCurrentRouterConfig(): Observable<ActivatedRoute> {
return this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.route),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
filter((route) => route.outlet === 'primary'),
// mergeMap(route => route.title)
);
}
// ngOnDestroy(): void {
// // unsubscribe subscriptions;
// }
// ngOnDestroy(): void {
// Object.keys(this.subscriptions).forEach(key => this.subscriptions[key].unsubscribe());
// }
}