generated from borjapazr/angular-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom-route-preload.strategy.ts
41 lines (34 loc) · 1.49 KB
/
custom-route-preload.strategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* eslint-disable import/no-deprecated */
import { ApplicationRef, Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { concat, EMPTY, first, Observable, switchMap, timer, toArray } from 'rxjs';
import { PlatformService } from '@core/services';
@Injectable({
providedIn: 'root'
})
export class CustomRoutePreloadingStrategy implements PreloadingStrategy {
private preloadedModules = new Set<Route>();
constructor(private readonly platformService: PlatformService, private applicationRef: ApplicationRef) {}
preload(route: Route, load: () => Observable<any>): Observable<any> {
const loadRoute = (delay: number) => {
this.preloadedModules.add(route);
const appIsStable$ = this.applicationRef.isStable.pipe(first(isStable => isStable === true));
const preloadTimer$ = timer(delay * 1000);
const preloadRouteOnceAppIsStable$ = concat(appIsStable$, preloadTimer$).pipe(
toArray(),
switchMap(() => load())
);
return delay > 0 ? preloadRouteOnceAppIsStable$ : load();
};
return this.shouldPreloadRoute(route) ? loadRoute(this.getDelay(route)) : EMPTY;
}
private shouldPreloadRoute(route: Route): boolean {
if (this.platformService.isServer) {
return false;
}
return !this.preloadedModules.has(route) && route.data && route.data['preload'];
}
private getDelay(route: Route): number {
return route.data && route.data['delayInSeconds'] ? route.data['delayInSeconds'] : 0;
}
}