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

Discussão em 'Angular' iniciado por Konrad Viltersten, Novembro 25, 2024.

  1. 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
    ...
    }

    Continue reading...

Compartilhe esta Página