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

Angular 14应用首次加载自动显示404错误页问题求助

解决方案

你的问题出在两个关键地方:缺少根路径的默认路由配置,以及NotFoundComponent未在模块中声明,以下是具体修复步骤:

1. 添加根路径默认路由

当前路由配置里没有匹配根路径(/)的规则,首次加载应用时,Angular找不到对应路由,就会匹配最后的通配符路由**,直接显示404页面。

修改app-routing.module.ts,添加根路径路由(假设你的首页组件是HomeComponent,如果没有请先创建该组件):

const routes: Routes = [
  { path: '', component: HomeComponent }, // 新增根路径路由
  { path: 'about-us', component: AboutUsComponent },
  { path: 'how-it-works', component: HowItWorksComponent },
  { path: '**', component: NotFoundComponent }, // 通配符路由必须放在最后
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

如果你的首页逻辑直接在AppComponent中,可以用重定向路由替代:

{ path: '', redirectTo: '/home', pathMatch: 'full' },
// 同时确保存在/home对应的路由配置

2. 注册NotFoundComponent

你的AppModule的declarations数组里没有包含NotFoundComponent,Angular无法识别该组件,必须补上:

@NgModule({
  declarations: [
    AppComponent,
    AboutUsComponent,
    HowItWorksComponent,
    NotFoundComponent // 新增这一行
  ],
  imports: [
    BrowserModule,
    AuthModule,
    UserModule,
    PublicModule,
    SharedModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

关于HashLocationStrategy

你之前尝试配置哈希路由策略无效,是因为问题核心不在路由模式,而是缺少根路径的匹配规则——即使切换哈希模式,根路径仍然没有对应路由,还是会触发404。

完成以上修改后,首次加载应用会自动进入首页,只有输入错误URL时才会显示404页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:10:31