import { Injectable } from "@angular/core" ; import { Route , Router } from "@angular/router" ; import { COMPONENT_MAP } from "../../../app.routing" ; import { ConfigService } from "../../config/config.service" ; import { LoggingService } from "../../logging/logging.service" ; import { PREFIX_VIEW_CONFIG , RouteData , ViewConfig , } from "./view-config.interface" ; import { UserRoleGuard } from "../../permissions/user-role.guard" ; /**
 * The RouterService dynamically sets up Angular routing from config loaded through the  ConfigService .
 *
 * You can define  ViewConfig objects in the central configuration and build the routing at runtime
 * rather than hard-coding the available paths and settings.
  @ Injectable ( { providedIn : "root" , } ) export class RouterService { constructor ( private configService , private router , private loggingService ) { } /**
     * Initialize routes from the config while respecting existing routes.
     */ initRouting ( ) { const viewConfigs = this . configService . getAllConfigs < ViewConfig > ( PREFIX_VIEW_CONFIG ) ; this . reloadRouting ( viewConfigs , this . router . config , true ) ; } param viewConfigs param additionalRoutes param overwriteExistingRoutes reloadRouting ( viewConfigs , additionalRoutes = [ ] , overwriteExistingRoutes = false ) { const routes = [ ] ; for ( const view of viewConfigs ) { const route = this . generateRouteFromConfig ( view ) ; if ( view . lazyLoaded ) { continue ; } if ( ! overwriteExistingRoutes && additionalRoutes . find ( ( r ) => r . path === route . path ) ) { this . loggingService . warn ( "ignoring route from view config because the path is already defined: " + view . _id ) ; continue ; } routes . push ( route ) ; } const noDuplicates = additionalRoutes . filter ( ( r ) => ! routes . find ( ( o ) => o . path === r . path ) ) ; routes . push ( ... noDuplicates ) ; this . router . resetConfig ( routes ) ; } private generateRouteFromConfig ( view ) { const path = view . _id . substring ( PREFIX_VIEW_CONFIG . length ) ; const route = { path : path , component : COMPONENT_MAP [ view . component ] , } ; const routeData = { } ; if ( view . permittedUserRoles ) { route . canActivate = [ UserRoleGuard ] ; routeData . permittedUserRoles = view . permittedUserRoles ; } if ( view . config ) { routeData . config = view . config ; } route . data = routeData ; return route ; } }