Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CanActivate to all path except some

I have a list of path I want to apply CanActivate to all path except some path.Is there any way in angular to discard some path. Currently I am applying canActivate to all the URLs.If there are lots of URL,We don't want to apply it to all the URL, I will apply to parent path. But if we apply to parent it will be applicable to all children also. Is there any way to discard some of the children.

const routes: Routes = [
    { path : '', component: UsersListComponent, canActivate:[AuthenticationGuard] },
    { path : 'add', component : AddComponent, canActivate:[AuthenticationGuard]},
    { path : ':id', component: UserShowComponent },
    { path : 'delete/:id', component : DeleteComponent, canActivate:[AuthenticationGuard] },
    { path : 'ban/:id', component : BanComponent, canActivate:[AuthenticationGuard] },
    { path : 'edit/:id', component : EditComponent, canActivate:[AuthenticationGuard] }
];
like image 903
Vikram Singh Avatar asked Sep 06 '25 03:09

Vikram Singh


1 Answers

It is not possible to discard some children, but you may break your routes in such a way that Guard applies to some and not to some,

Try below,

 {
    path: 'parentPath',
    component: ParentComponent,
    canActivate: [AuthGuard],
    children: [
      {path : 'child1', component: ChildComponent1},
      {path : 'child2', component: ChildComponent2}
    ]
  },
  {
    path: 'parentPath',
    component: ParentComponent,
    children: [
      {path : 'child3', component: ChildComponent3}
    ]
  }

If you design your routes like above, Guards will only be applied to child1 and child2, and not on child3.

In this way you can easily apply Guard at parent level for some of the children.

Here is a Plunker!!

like image 144
Madhu Ranjan Avatar answered Sep 07 '25 22:09

Madhu Ranjan