1

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?

ldgorman
  • 1,553
  • 1
  • 14
  • 39
  • There's not enough information here. We need to see how you set up the `APP_CONFIG` injection token besides you can't inject into a module definition, only into directives, components, services etc. – Avin Kavish Jun 05 '19 at 12:06
  • @AvinKavish Is it possible to push to routes in a component and have appModule consume those routes? – ldgorman Jun 05 '19 at 12:12
  • https://stackoverflow.com/questions/42928030/is-it-possible-to-build-add-routes-dynamically-in-angular-2 It's not the app module consuming routes, you are just importing the router in the app module while passing it some default routes. – Avin Kavish Jun 05 '19 at 12:13
  • 1
    Rather than pushing each remote route, I would recommend having a catch all route like so `help/**` and processing all redirects from a single component/guard whose sole job is to parse the route and perform a redirect. – Avin Kavish Jun 05 '19 at 12:18

1 Answers1

0

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.

Community
  • 1
  • 1
ldgorman
  • 1,553
  • 1
  • 14
  • 39