angularroutesazure-ad-msalangular-routermsal-angular

How to eliminate the verbose pattern of canActivate/canDeactivate in Angular?


My routing is set up like this (main parent node with a bunch of child sub nodes).

export const routes: Routes = [
  { path: "", component: HomeComponent },
  { path: "profile", component: ProfileComponent },
  {
    path: ":itemId", component: TabsComponent, children: [
      { path: "a", component: ComponentA, canActivate: [MsalGuard], canDeactivate: guard },
      { path: "b", component: ComponentB, canActivate: [MsalGuard], canDeactivate: guard },
      { path: "c", component: ComponentC, canActivate: [MsalGuard], canDeactivate: guard },
      ...
    ], canActivate: [MsalGuard]
  },
  ...
  { path: "**", component: BoomComponent },
];

I noticed that the canActivate: [MsalGuard] for the tabs (i.e. the last one) isn't really useful, because each sub-placed child has it too. Then, it stroke me: is there a way to specify canActivate and canDeactivate so that it actually influence the individual sub-paths?

Something along the lines of the below (which I, naturally, tested and discovered that it won't do what I want).

...
{
  path: ":itemId", component: TabsComponent, children: [
    { path: "a", component: ComponentA },
    { path: "b", component: ComponentB },
    { path: "c", component: ComponentC },
    ...
    ], canActivate: [MsalGuard], canDeactivate: guard
  ...
}

Solution

  • From the MSAL Guard - Github Documentation the MsalGuard Supports CanActivateChild and canLoad. So could you try CanActivateChild guard instead of canActivate.

    ...
    {
      path: ":itemId", component: TabsComponent, children: [
        { path: "a", component: ComponentA },
        { path: "b", component: ComponentB },
        { path: "c", component: ComponentC },
        ...
        ], canActivateChild: [MsalGuard], canDeactivate: guard
      ...
    }