import { Injectable } from '@angular/core'; import { PreloadingStrategy, Route } from '@angular/router'; import { isEqual } from 'lodash'; import { Observable, of } from 'rxjs'; import { routes } from '../../../app.routes'; import { PortalDeterminationService } from './portal-determination.service'; @Injectable({ providedIn: 'root' }) export class GCPreloadingStrategy implements PreloadingStrategy { constructor ( private portal: PortalDeterminationService ) { } private routes = routes; // for testing // look for a route (searchRoute) in the route definition (routeDef) and all children recursively findIfInChildRecursive (searchRoute: Route, parentRoute: Route): boolean { return isEqual(parentRoute, searchRoute) || (parentRoute.children ? parentRoute.children.some(child => this.findIfInChildRecursive(searchRoute, child)) : false); } getCurrentRouteRoot () { return this.routes.find(wrapper => wrapper.path === this.portal.routeBase); } getShouldLoad (route: Route) { return this.routes.find(wrapper => { return this.findIfInChildRecursive(route, wrapper); }); } preload (route: Route, load: () => any): Observable { const desiredRoot = this.getShouldLoad(route); const currentRouteRoot = this.getCurrentRouteRoot(); // if it isn't in the parent routes (from a module loaded off of the parent module) OR it is under the right parent route, we can preload if (!desiredRoot || desiredRoot === currentRouteRoot) { return load(); } return of(null); } }