如何将CanActivate应用于除

时间:2017-08-13 04:06:50

标签: javascript angular2-routing

我有一个路径列表我希望将CanActivate应用到除了某个路径之外的所有路径。是否有任何方法可以放弃某些路径。 目前我正在将canActivate应用于所有URL。如果有很多URL,我们不想将其应用于所有URL,我将应用于父路径。 但是,如果我们申请父母,它也适用于所有孩子。有没有办法丢弃一些孩子。

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] }
];

1 个答案:

答案 0 :(得分:0)

不可能丢弃一些孩子,但是你可能会以某种方式打破你的路线,使Guard适用于某些人,而不是某些人,

尝试以下,

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

如果您设计上述路线,则Gurads仅适用于child1child2,而不会应用于child3

通过这种方式,您可以轻松地在父级别为某些孩子申请Guard。

这是Plunker !!

希望这会有所帮助!!