angularangular-routerangular-standalone-componentsangular-route-guards

How do I apply the `canActivateFn` to all routes in a standalone Angular application?


In module-based applications, to add a guard to all routes at once, i can pass it as the second parameter to the RouterModule.forRoot function.

RouterModule.forRoot(routes, { canActivate: [AuthGuard] })

How i can do this with provideRouter function?

Docs did not help.

I try use this call

provideRouter(routes, { canActivate: [authGuard], })

but it didn't work.


Solution

  • There is no property canActivate on extraOptions in forRoot so the function is never called at all.

    If you want to achieve this, set the canActivate function in the array, for all the root components in routing, this will run for all route changes in the application.

    This example is not standalone, but focus on the routing configuration, since that is what I am trying to demonstrate. The running of the function for all route changes in the application.

    @Injectable({
      providedIn: 'root',
    })
    export class testActivate implements CanActivate {
      constructor() {}
    
      canActivate(route, state): boolean {
        console.log('running');
        return true; // we can try wil false and it will not redirect to the path
      }
    }
    
    const routes: Routes = [
      { path: '', component: HomeComponent, canActivate: [testActivate] },
      { path: 'home', component: HomeComponent, canActivate: [testActivate] },
      { path: 'contact', component: ContactComponent, canActivate: [testActivate] },
      {
        path: 'products',
        component: ProductsComponent,
        canActivate: [testActivate],
      },
      {
        path: 'product/:id',
        component: ProductComponent,
        canActivate: [testActivate],
      },
      { path: 'users', component: UsersComponent, canActivate: [testActivate] },
      {
        path: 'user/:id/:name',
        component: UserComponent,
        canActivate: [testActivate],
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule],
    })
    export class AppRoutingModule {}
    

    Stackblitz Demo