Friday, 15 November 2019

Computed object/Map/dictionary keys in Ahead of Time compiled Angular application

I'm working on an Angular app where we want to have the routes defined as Enums. Then, for the enums declare the specific routes that they point to. The Enums are bound to string values that match keys in CMS-system.

For instance, our first naive implementation was:

mainRoutes.ts

export enum RouteKey {
  Dashboard = "dashboard",
  Summary = summary"
}

export routes = {
  [RouteKey.Dashboard]: "dashboard",
  [RouteKey.Summary]: "summary"
}

In app.routing.module.ts, these two variables are then imported and used like this:

...
{
  path: routes[RouteKey.Dashboard],
  component: DashboardComponent,
},
{
  path: routes[RouteKey.Summary],
  component: SummaryComponent,
}

This code runs fine when running in development, however with ahead-of-time compilation it fails during compilation, with the message expression form not supported visible in the terminal, pointing to the first line that uses the computed entry ([RouteKey.Dashboard]: "dashboard").

Fair enough. We then attempted another approach using Javascript Map objects, like so:

...
export const routes = new Map();
routes.set(RouteKey.Dashboard, "dashboard");
routes.set(RouteKey.Summary, "summary");

With the references in app.routing.module.ts updated to routes.get(***) instead of routes[***].

and again the code runs fine when running development mode, and this time the code builds correctly.

However, when hosting the build and visiting the site, I get the following error in the browser:

Invalid configuration of route '': routes must have either a path or a matcher specified

Does anyone know how I can solve this issue? Is it at all possible to have a computed dictionary object for holding routes in an Angular application that uses Ahead of Time-compilation?



from Computed object/Map/dictionary keys in Ahead of Time compiled Angular application

No comments:

Post a Comment