Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a dynamic route guard in angular from a JSON value?

I am trying to add the route guard in my angular app.

I am building the routes dynamically from a JSON which has the following structure

 {
      "path": "software-upgrade",
      "title": "Software Upgrade",
      "canActivate": "AuthGuard",  // This is the route guard name
      "isMFE": true,
      "loadRemoteModule": {
        "type": "manifest",
        "remoteName": "software-upgrade",
        "exposedModule": "./Module"
      },
      "moduleName": "SoftwareUpgradeModule"
    },

I am using the value of canActivate while building the route like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

routeArr.push({
          path: route.path,
          canActivate: [AuthGuard],   // this works
          // canActivate: [route.canActivate], // this does not work even though it is fetching the same value from JSON
        });

I get the following error in console if i use the value from the JSON but the same thing works if I directly specify the value of the guard.

error shown in console

Is there any way of handling this?

>Solution :

You need to create an object map, where the key will be the authGuard and the value will be AuthGuard (the actual import)

import { AuthGuard } from 'some path';

export const DYNAMIC_ROUTING_MAP = {
    'authGuard': AuthGuard,
    ...
}

Then on the dynamic routing, we can simply get the reference and set it!

routeArr.push({
   path: route.path,
   canActivate: [DYNAMIC_ROUTING_MAP[route.canActivate]], // <- changed here!
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading