Angular路由跳转异常,手动修改地址仍加载AppComponent问题求助
问题修复方案
核心问题原因
- 路由配置错误:不应该将根组件
AppComponent注册到路由表中,AppComponent是应用的启动根组件,所有路由匹配到的组件都需要渲染在它内部的<router-outlet>占位符位置,注册为路由组件会导致根组件重复加载,覆盖路由渲染逻辑 - 遗漏路由出口:
app.component.html中没有添加<router-outlet>标签,匹配到的路由组件没有渲染入口
具体修改步骤
- 修改
AppRoutingModule的路由配置,移除AppComponent的路由项,调整为以下内容:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ // 根路径重定向到home页 {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'home', component: HomeComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
- 修改
app.component.html文件,添加路由出口标签,示例内容如下:
<!-- 可以保留全局通用内容,比如顶部导航栏 --> <router-outlet></router-outlet>
验证效果
修改完成后重启开发服务,访问localhost:4200/home即可正常加载HomeComponent的内容,访问根路径localhost:4200会自动重定向到home页。
内容的提问来源于stack exchange,提问作者KRdg
相关产品推荐
相关产品推荐

