Angular: 如何防止通过浏览器直接访问惰性子模块路由

Angular: How to prevent direct access to lazy child module route via browser

我正在使用 Angular9 开发多模块应用程序。这是我的主要应用程序路由模块。

这里是 AppRoutingModule,它会延迟加载 DemoModule

const routes: Routes = [
{
    path: '',
    component: AdminLayoutComponent,
    canActivate: [SecGuard],
    children: [
      {
        path: 'demo',
        loadChildren: () => import('demo').then((m) => m.DemoModule),
       },
      { path: 'not-found-page', component: NotFound404PageComponent, canActivate: [SecGuard] },
    ],
  },

  { path: '**', redirectTo: 'not-found-page' },
];

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

这里是DemoRoutingModule

的代码
export const CTS_ROUTES: Routes = [{ path: 'dashboard', component: DashboardComponent, canActivate: [SecGuard] }];

@NgModule({
   imports: [RouterModule.forChild(CTS_ROUTES)],
   exports: [RouterModule],
})
export class DemoRoutingModule {}

这是我的 AppModule

@NgModule({
 declarations: [AppComponent],
   imports: [
     BrowserModule,
     BrowserAnimationsModule,
      CommonModule,
     CoreModule.forRoot(configuration),
     DemoModule,
     AppRoutingModule,
      ],
     providers: [],
     bootstrap: [AppComponent],
   })
  export class AppModule {}

现在访问http://localhost:4200/demo/dashboard一切正常

但是当我尝试访问 http://localhost:4200/dashboard 时,我不想这样做。然后结果如下图。

我只想通过父路径 /demo/dashboard 访问子组件(在本例中为 DashboardComponent)。

我怎样才能实现这个功能?有什么想法吗?

在你的守卫中,你可以创建一个状态(boolean fromParent)。

当您访问您的父组件 (demo/dashboard) 时,您将其设置为 true。 然后,当您尝试访问您的子组件时,您检查 fromParent,如果它是真的,那么您就可以开始,如果不是,您将重定向到另一个页面。 一旦成为子组件,请不要忘记重置 fromParent。

正如@GowthamRajJ 评论的那样,Angular 从路由模块中解析延迟加载的模块。无需在 AppModule 中导入延迟加载模块。