【问题标题】:How to apply canActivate guard for all routes(master route and all sub routes) in Angular如何在 Angular 中为所有路由(主路由和所有子路由)应用 canActivate 保护
【发布时间】:2020-02-26 08:51:40
【问题描述】:

我使用 Angular Guard 来保护我的路由,我在主路由中添加 canActivate attr 并且它工作正常,而对于子单路由(ReportsRou​​teModule/RequestsRou​​teModule...),如果我想启用守卫,我还需要在每条路线中设置 canActivate ,我认为使用角度守卫是一种不好的方式,而且会浪费很多时间。那么有什么办法可以避免它并在主路由中管理它。

请看我的应用结构和一些代码如下: 1. 应用结构:

 |-- app.module.ts
 |-- app-routing.module.ts(master route)
 |-- app.component.ts
 |-- report
    |-- report-route.module.ts(sub route)
    |-- report-aa
    |-- report-bb
    |-- report-cc
 |-- request
    |-- request-route.module.ts(sub route)
    |-- request-aa
    |-- request-bb
    |-- request-cc
 |-- etc.
  1. 代码: 主路线
const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  // providers: [AuthGuard]
})
export class AppRoutingModule {

子路线:

const routes: Routes = [
  {
    path: 'reports',
    canActivateChild: [AuthGuard],
    children: [
      {path: '', redirectTo: 'reports', pathMatch: 'full'},
      {path: 'A', component: AReportsComponent},
      {path: 'B', component: BReportsComponent},
      {path: 'C', component: CReportsComponent},
    ]
  }

];
@NgModule({
  imports: [
    RouterModule.forChild(routes),
  ],
  declarations: [
    AReportsComponent,
    BReportsComponent,
    CReportsComponent,
   ]
})
export class ReportsRouteModule {

}

【问题讨论】:

  • 请同时发布您的 authguard。

标签: angular angular-router-guards canactivate canactivatechild


【解决方案1】:

您可以将路由放在父路由内,并仅在父路由上使用canActive。这样,守卫也将匹配所有子路由。

示例代码

{
    path: "", 
    canActivate: [ParentAuthGaurdService], 
    children: [
        { path: "admin-dashboard", component: AdminDashboardComponent },
        { path: "admin/user", component: UserCrudComponent },
        { path: "admin/product", component: ProductCrudComponent }
    ]
}

【讨论】:

    【解决方案2】:

    按照建议,我在子路由中添加了canActivate,它工作正常。

    【讨论】:

      【解决方案3】:

      一些关于路由器内部的信息,这将帮助您理解为什么将canACtivateGuards 添加到每个子模块的根路由不是一个坏习惯。

      当您使用RouterforRootforChild 时,它会将子模块routes 合并到父模块routes 数组中。所以这些路由成为兄弟路由。这意味着,您必须将canActivate 保护添加到每个子模块的顶级路由。

      如果您不想这样做,则必须将所有其他子路由作为应用程序路由中的一个父路由的子路由,如下面的答案中所述(这可能不是您想要的)。

      【讨论】:

        猜你喜欢
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多