Trying to understand the differences between CanActivate and CanActivateChild

前端 未结 3 1322
后悔当初
后悔当初 2021-02-19 21:20

So, I\'m trying to protect the access to several routes by using guards. I\'m using the following routes to do so :

const adminRoutes : Routes = [
  {
    path:          


        
3条回答
  •  死守一世寂寞
    2021-02-19 21:43

    In my view, the CanActivate is used to restrict access from a certain path and all the sub-paths and CanActivateChild is used to restrict access to a specific group inside the CanActivate path.

    Example:

    {
      path: 'admin',
      component: AdminComponent,
      canActivate: [AuthGuardService],
      children : [
        {
          path: 'books', component: ...,
        },
        {
          path: 'authors', component: ...,
        },
        {
          path: 'payments',
          canActivateChild: [AuthGuardService],
          children: [
            {
              path: 'list', component: ...
            },
            {
              path: 'list/:id', component: ...
            }
          ]
        }
      ]
    }
    

    Because you need two types of validations, you cannot have two canActivate methods, so you need the canActivateChild for checking the permision inside the canActivate path. Obviously, you can create a different guard service (AuthGuardForChildrenRoutes) and still use canActivate method, but that's not the point.

提交回复
热议问题