Angular根路径重定向至sign-in却显示PageNotFound问题排查
问题原因与解决方案
这事儿很明显——Angular根本不知道你定义在AuthRoutingModule里的sign-in路由存在!
你看,虽然你在AppRoutingModule里把根路径重定向到了/sign-in,但如果包含AuthRoutingModule的AuthModule没有被导入到你的AppModule中,Angular的路由系统就找不到sign-in对应的路由配置,自然就会匹配到通配符路由**,显示PageNotFoundComponent。
具体修复步骤
确保
AuthModule正确导入AuthRoutingModule
先检查你的AuthModule(如果还没创建,就新建一个),要把AuthRoutingModule加到imports数组里:// auth.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AuthRoutingModule } from './auth-routing.module'; import { SignInComponent } from './components/sign-in/sign-in.component'; @NgModule({ declarations: [SignInComponent], imports: [ CommonModule, AuthRoutingModule // 必须导入子路由模块 ] }) export class AuthModule { }把
AuthModule导入到AppModule
然后在AppModule的imports数组里添加AuthModule,这样Angular才能加载到sign-in的路由配置:// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AuthModule } from './auth/auth.module'; // 导入AuthModule import { PageNotFoundComponent } from './shared/page-not-found/page-not-found.component'; @NgModule({ declarations: [ PageNotFoundComponent ], imports: [ BrowserModule, AppRoutingModule, AuthModule // 加到这里 ], providers: [], bootstrap: [/* 你的根组件,比如AppComponent */] }) export class AppModule { }
额外验证点
- 确认你的
SignInComponent已经在AuthModule的declarations里声明了(如果是独立组件,则需要在路由配置中使用loadComponent替代直接引用组件) - 检查路由配置的
pathMatch:你的sign-in路由和根路径重定向都用了pathMatch: 'full',这部分配置是正确的
这样修改之后,当你访问根路径时,Angular就能找到sign-in的路由,正确加载SignInComponent而不是404页面了。
内容的提问来源于stack exchange,提问作者igor
相关产品推荐
相关产品推荐

