Angular 5子模块路由配置失效报错,寻求解决方案
Hey there! Let's work through your Angular 5 routing problem together. I've reviewed your code and found a few critical issues that are causing your routes to fail. Here's how to fix them step by step:
1. Wrong Placement of <router-outlet>
Your index.html has <router-outlet> outside of <app-root>—this is incorrect. Angular's router outlet needs to live inside your root component's template so it can render routed components within your app's core structure.
Fix:
Move <router-outlet> from index.html to app.component.html:
<!-- index.html (after fix) --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Web</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html>
<!-- app.component.html --> <router-outlet></router-outlet>
2. Incorrect Import Order in AppModule
You’ve imported AppRoutingModule before BrowserModule—Angular requires BrowserModule to load first because routing functionality depends on it.
Fix:
Adjust the imports order in app.module.ts:
// app.module.ts (fixed imports section) imports: [ BrowserModule, AppRoutingModule ],
3. Complete the WebModule Routing Setup
Your WebModule is incomplete, and it needs its own child routing configuration to work with lazy loading. Here’s how to finish setting it up:
Step 1: Create web-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; // Import your WebModule components here (example): // import { HomeComponent } from './home/home.component'; const routes: Routes = [ // Define your child routes here (example): // { path: '', component: HomeComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class WebRoutingModule {}
Step 2: Update web.module.ts
Make sure to import WebRoutingModule and declare your module’s components:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { WebRoutingModule } from './web-routing.module'; // Import your components here (example): // import { HomeComponent } from './home/home.component'; @NgModule({ declarations: [ // Declare your WebModule components here (example): // HomeComponent ], imports: [ CommonModule, WebRoutingModule ] }) export class WebModule {}
4. Verify Lazy Loading Syntax
Your lazy loading syntax loadChildren: './web/web.module#WebModule' is correct for Angular 5, but double-check that the file path to WebModule is accurate (relative to the location of app-routing.module.ts).
After making these changes, restart your Angular dev server and test the routes—they should work as expected!
内容的提问来源于stack exchange,提问作者Wai Yan Hein

