angularangular-routingangular-routerangular-router-guardsauth-guard

Angular how to disable authGuard on particular child page


can anyone suggest best way to disable authguard (applied on parent level) on a single child page.

ROUTES:Routes = [
    {
        path: '',
        component: AdminComponent,
        children: [
            {
                path: '',
                pathMatch: 'full',
                data: { title: 'Home' },
                loadChildren: 'src/app/admin/dashboard/modules/dashboardRouteModule#DashboardRouteModule',
            },
            {
                path: 'dashboard',
                redirectTo: ''
            },
            {
            path : 'blog',
            data: { title: 'Blog', breadcrumb: 'Blog' },
            loadChildren: 'src/app/admin/blog/modules/blogRouteModule#BlogRouteModule'
            },
             {
                path: '**',
                component: NotFoundComponent
            }],
    canActivate: [ AuthGuard ]}];

Blog Route Module

ROUTES:Routes = [
    {
        path: '',
        component: BlogComponent,
        resolve: {
            routeValues: BlogCreateResolve
        },
    },
    {
        path: ':id',
        resolve: {
            routeValues: BlogEditResolve
        },
        runGuardsAndResolvers: 'always',
        children: [
            {
                path: '',
                component: BlogEditComponent,
                canDeactivate: [CanDeactivateGuard],
            },
            {
                path: 'list',
                data: { title: 'BlogList', breadcrumb: 'List' },
                component: BlogListComponent,
                resolve: {
                    list: BlogListResolve
                }
            }]}]

Currently, all pages are restricted and require a login but I want to disable authguard for 'list' route so that page can be viewed without login.

Thanks


Solution

  • You can pass data to your guard on each route, and in that way to exclude certain routes from it. for example:

      {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuard],
        data: [{ noLogin: true}],
      },
    

    and in the guard:

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ):
        | Observable<boolean | UrlTree>
        | Promise<boolean | UrlTree>
        | boolean
        | UrlTree {
        const noLogin= route.data[0].noLogin;
       
        if (noLogin) {
           return true;
        }
         
      }