Angular项目默认路由/无法访问,/home正常,如何修复?
Let's break down why your default route isn't working and how to fix it:
1. The Critical Issue: Misuse of RouterModule.forRoot()
Your MainRoutingModule is incorrectly calling RouterModule.forRoot() inside its ngOnInit method. The forRoot() method is designed to be called exactly once in your root AppModule—using it in a feature module like MainModule causes conflicts in the router configuration, which is likely why your default route / isn't working even though /home does.
2. Step-by-Step Fixes
A. Correct the MainRoutingModule
Remove the OnInit implementation and the invalid forRoot() call. Your routing module should only use forChild() for feature routes:
const routes: Routes = [ { path: '', component: HomeComponent, canActivate: [AnonymousGuard] }, { path: 'home', component: HomeComponent, canActivate: [AnonymousGuard] }, { path: '**', redirectTo: '', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class MainRoutingModule { constructor() { } }
B. Move Scroll Position Configuration to AppModule
If you want to enable scrollPositionRestoration, add that configuration to the forRoot() call in your root AppModule where it belongs:
const routes: Routes = [ { path: '', loadChildren: './modules/main/main.module#MainModule' }, ]; @NgModule({ declarations: [ AppComponent, ], imports: [ RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }), ], providers: [ AuthService, UtilService, UserService ], bootstrap: [AppComponent] }) export class AppModule { }
C. (Optional) Fix Duplicate AuthService Provider
You're providing AuthService in both AppModule and MainModule. In Angular, this creates two separate instances of the service (one for each module's injector). Unless you intentionally need a separate instance in MainModule, remove it from the MainModule providers to ensure a singleton service:
@NgModule({ declarations: [ PressComponent, LegalComponent ], providers: [ // Remove AuthService here unless you need a module-specific instance ], imports: [ HomeModule, MainRoutingModule, ] }) export class MainModule { }
Why This Works
- By removing the duplicate
forRoot()call, you let the router properly handle the parent-child route hierarchy fromAppModuletoMainModule. - The default route
/now correctly maps to the empty path inMainRoutingModule, which loadsHomeComponentas expected.
内容的提问来源于stack exchange,提问作者methuselah

