Angular 8 - 延迟加载 - 奇怪的子路由行为

Angular 8 - Lazy Loading - Weird Child Route Behaviour

我有一个 angular 8 应用程序,每个功能模块都包含一个 *-routing.module.ts 文件,其中包含到它的各个组件的路由。

目前我有2个功能模块,一个叫"Tasks",一个叫"Clients"。

两者的设置方式相同。这是我的 app.routing.ts:

// Task Pages
{ path: 'tasks', loadChildren: './tasks/tasks.module#TasksModule' },

// Client Pages
{ path: 'clients', loadChildren: './clients/clients.module#ClientModule' },

现在由于某种原因,这两个模块的行为很奇怪。在 clients-routing.module.ts 中,我在路由前加上 "clients":

  const routes: Routes = [
    { path: 'clients', component: ClientListComponent, canActivate: [AuthGuard] },
    { path: 'clients/new', component: ClientCreateComponent, canActivate: [AuthGuard]},
    { path: 'clients/:id', component: ClientDetailComponent, canActivate: [AuthGuard]},
    { path: 'clients/:id/edit', component: ClientEditComponent, canActivate: [AuthGuard]},
];

一切都按预期进行。导航到 http://baseurl/clients lists all clients, navigating to http://baseurl/clients/1 会导航到正确的客户详细信息等。

但是,对于 tasks-routing.module.ts,如果我像在客户端文件中一样包含任务前缀,那么它就不起作用,none 的路线按预期工作,相反,我需要这样做:

    const routes: Routes = [
    { path: '', component: TaskListComponent, canActivate: [AuthGuard] },
    { path: 'new', component: TaskCreateComponent, canActivate: [AuthGuard] },
    { path: ':id', component: TaskDetailComponent, canActivate: [AuthGuard] },
];

此时,预期路线起作用,例如 http://baseurl/tasks listing all tasks, http://baseurl/tasks/23 显示任务 23 详细信息等。

它们为什么不同?我似乎看不出这两个模块的路由会有所不同的任何原因。

这好像是注册路由时使用RouterModule.forRoot()RouterModule.forChild()的区别

我怀疑您的客户端路由使用的是 forRoot 方法,而任务使用的是 forChild 方法,因此存在差异。

Angular 风格指南推荐:

Only call RouterModule.forRoot() in the root AppRoutingModule (or the AppModule if that's where you register top level application routes). In any other module, you must call the RouterModule.forChild method to register additional routes.

https://angular.io/guide/router