You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目默认路由/无法访问,/home正常,如何修复?

Fix for Default Route '/' Not Working in Angular App

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 from AppModule to MainModule.
  • The default route / now correctly maps to the empty path in MainRoutingModule, which loads HomeComponent as expected.

内容的提问来源于stack exchange,提问作者methuselah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:28