Search code examples
angularconfigangular-routing

Populate a route with an external URL from config


My routes are defined as:

export const routes: Routes = [
  { path: "", redirectTo: "/datasets", pathMatch: "full" },
  {
  path: "help/youtube",
  canActivate: [RedirectGuard],
  component: RedirectGuard,
  data: {
    externalUrl:  "https://youtube.com"
  }
},
...
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}

Where redirect guard is a module that handles external URLs.

Instead of hard coding externalUrl I need to fetch it from my appConfig but I cant access appConfig without a constructor like:

constructor(@Inject(APP_CONFIG) private appConfig) {}

as appConfig is set up as a module with injection token like:

export const APP_CONFIG = new InjectionToken<AppConfig>("app.config");

So i tried to add this Inject to my AppRoutingModule but to no success.

How can I access appConfig to populate this external URL?


Solution

  • So i found a solution.

    access appConfig from within my redirect-guard (which i took from here)

    @Injectable()
    export class RedirectGuard implements CanActivate {
    
      constructor(private router: Router, @Inject(APP_CONFIG) public appConfig: AppConfig) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    
    
          window.location.href = this.appConfig[route.data["externalUrl"]];
          return true;
    
      }
    }
    

    Passing in the config item name as data["externalUrl"] which i will rename to something more appropriate shortly. This will mean hard coded URLs wont work, but i can live with this.

    The route definition in app-routing.module looks like this:

    {
        path: "help/ingestManual",
        canActivate: [RedirectGuard],
        component: RedirectGuard,
        data: {
          externalUrl:  "ingestManual"
        }
      }
    

    Where ingestManual is the item defined in my config file.

    This has allowed me to redirect app routes to external URLs.