typescript - Angular 5 เส้นทางลูกถูกโหลดที่ router-outlet ระดับรากเมื่อใช้ loadChildren ในการกำหนดเส้นทาง
ฉันมีคอมโพเนนต์แอปหลักที่มี router-outlet และเส้นทางถูกโหลดจากเส้นทางของโมดูลหน้าแรกซึ่งใช้การโหลดแบบ lazy loading ด้วย loadchildren ในเส้นทางย่อยของมัน มี router-outlet ในคอมโพเนนต์หน้าแรก และยังมี router-outlets ในทุกโมดูลย่อยของหน้าแรกที่โหลดแบบ lazy routes เส้นทางทำงานได้ดี แต่เส้นทางย่อยก็ถูกโหลดใน root router-outlet ด้วย ตัวอย่าง:- คอมโพเนนต์ 'testCreateComponent' ถูกโหลดด้วย localhost:4200/test/create และยัง localhost:4200/create ด้วย
ระดับตัวอย่างโค้ดมีดังนี้:-
app.component.html
<div>app</div>
<router-outlet></router-outlet>
แอป-routing.module.ts
export const APP_ROUTES: Routes = [
{path: '**', redirectTo: '', pathMatch: 'full'}
];
home.component.html
<div>home</div>
<router-outlet><router-outlet>
home-routing.module.ts
const routes: Routes = [{
path: '',
component: HomeComponent,
canActivate: [LoggedUserGuard],
canActivateChild: [AuthGuard],
children: [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{
path: 'test',
loadChildren: () => testModule
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
breadcrumb: 'Dashboard'
}
},
{
path: 'dummy',
loadChildren: () => dummyModule,
}
]
}];
testComponent.html
<div>Test</test>
<router-outlet></router-outlet>
test-routing.module.ts
const routes: Routes = [{
path: '',
component: TestComponent,
children: [
{path: '', component: ListComponent,
data: {
breadcrumb: 'List'
}},
{path: 'create', component: testCreateComponent},
{ path: 'detail/:id',
component: TestEditComponent,
}
]
}];
คำตอบ #1
ปัญหาน่าจะมาจากวิธีที่คุณนำเข้ามอดูลที่โหลดแบบขี้เกียจของคุณ
เรามีปัญหาคล้ายกันกับโมดูลที่โหลดแบบขี้เกียจ ซึ่งถูกนำเข้าอย่างชัดเจน/อย่างเร่งด่วนโดยผิดพลาดในส่วนการนำเข้า TypeScript ที่ด้านบนของไฟล์โมดูล (แทนที่จะนำเข้าเฉพาะในฟังก์ชัน loadChildren เท่านั้น)
เพื่อที่จะหาพวกมันได้ง่ายในโปรเจกต์ขนาดใหญ่ ฉันคิดว่าเรากำหนดค่าเราเตอร์ด้วย preloadingStrategy: PreloadAllModules, ออกจากระบบ router.config และตรวจสอบเส้นทางและคอมโพเนนต์ของมัน การลบการนำเข้าออกจากส่วนการนำเข้า TypeScript ที่ด้านบนของโมดูล (แล้วเหลือไว้เฉพาะแบบอินไลน์) แก้ปัญหาได้
ลองลบออก
import { testModule } from "./path/to/file/containing/test.module";
จากส่วนบนของไฟล์ของคุณและใช้เพียงสิ่งต่อไปนี้ในเส้นทาง
loadChildren: () => import("./path/to/file/containing/test.module").then((m) => m.testModule)
ตรวจสอบเอกสาร Angular ด้วย: การแก้ไขปัญหาการโหลดโมดูลแบบ Lazy-loading
