Trying to understand the differences between CanActivate and CanActivateChild

前端 未结 3 1499
误落风尘
误落风尘 2021-02-19 21:10

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:32

    Both are important because you may have differing requirements where a user can get to the root component, but may not meet conditions for child components.

    Example: You could have a situation where a user must be authenticated to navigate to the root component, but must have permission 'x' to get to child components. In cases like this, canActivateChild saves a lot of typing from having to add canActivate guards to each of the children.

    EDIT:

    For example, you may have an Admin Module where all routes need to be guarded against unauthorized entry:

      {
        path: 'admin',
        component: AdminComponent,
        canActivate: [ AuthGuardService ],
        children : [
          {
            path: '', component: ...,
          },
          {
            path: 'manage-users', component: ...,
          },
          {
            path: 'manage-roles', component: ...,
          }
        ]
      }
    

    This would need to be protected from the top down. No unauthorized access to any of the routes, including the root and children. In this situation canActivate at the root level works great to protect everything.

    But you may also have times where you have a Feature module where only certain children need to be guarded:

      {
        path: 'featureA',
        component: ...,
        canActivateChild: [ AuthGuardService ],
        children : [
          {
            path: 'manage-feature', component: ...,
          },
          {
            path: 'manage-members', component: ...,
          }
        ],
        {path: 'featureB', component: ...}
      }
    

    In this situation, maybe all users need to get to the root components 'featureA' and 'featureB', but only certain users need to be able to navigate to the child routes of 'featureA'. In this case it is easier to use one guard at the root level to protect the children, but not the root itself. The alternative is to put canActivate guards on each child route, which could get tedious.

    It really all depends upon your requirements, but it can be nice to have both options of canActivate and canActivateChild.

提交回复
热议问题