Angular: whether the current route or page is protected or guard actice

589 Views Asked by At

I am using Angular 9 and I would like to know is there a possibility to check whether the current page is protected/guarded or not during APP_INITIALIZER phase.

I am using the APP_INITIALIZER to set some pre-configuration for the app but during this process I have to know whether the current route/path/page is protected. The route can be of lazy-module and this route or routes is/are not available in the this.router.config.

Currently, working solution, is to read all the routes recursively and then create a list of all routes available in app and them match the current route path within list, which is pretty bad solution to me. I am looking for a correct way to implement this solution.

Please help,

Thanks in advance,

Always available for the more info if needed.

EDIT: Adding an example

Suppose I have a list of routes:

App-routing.modules.ts

[
  {path: '', component: XY},
  {path: 'profile', component: Profile},
  {path: 'submodule', load: LoadSubModule},
  {path: '..', load: LoadSubModule2, canActivate: [AuthGuard]},
  {path: '..', load: LoadSubModule3},
]



LoadSubModule routing module
[
   {path: '', component: yz},
   {path: 'form', component: Form, canActivate: [AuthGuard]},
   {path: 'subSubModule', load: LoadSubSubModule, canActivate: [AuthGuard]},
]

If I land on the page domain.com/submodule/form/ I want to know that the route /submodule/form is guard or not while App_Initilizer is being done.

1

There are 1 best solutions below

2
On

You can get the list of routes declared in your router with this


constructor(private router: Router) {
  console.log(this.router.config);
}

You'll get all the routes defined within your current router, as well as their paths, components, guards, etc.

You can then use a recursive function to check for all routes having a guard.