Angular <router-outlet>重复渲染页面、路由跳转重定向问题排查
问题原因
两个问题本质都是路由基础配置错误导致的,和命名路由出口、home组件本身的写法没关系:
- 页面重复渲染:根路径
''错误绑定了AppComponent。AppComponent是Angular应用启动时就会全局挂载的根壳组件,本身就包含了<router-outlet>,当路由匹配到根路径时,又会把AppComponent作为路由组件渲染到出口里,形成套娃,自然出现两个相同页面上下叠加的效果。 - 加命名出口后
/articles跳回首页:一是你给主路由出口加name属性后,默认路由规则不会往命名出口渲染内容,套娃问题暂时消失,但这属于误打误撞,不是正确解法;二是你的路由表根本没有定义/articles这个路径,所有未匹配的路径都会被通配符规则**重定向到根路径/,自然跳不过去。
修复方案
按以下步骤改完就能正常运行:
- 移除路由表中根路径对
AppComponent的绑定,根路径应该绑定作为首页的HomeComponent,同时给根路径加pathMatch: 'full'避免前缀匹配干扰其他路由。 - 在路由表中补上缺失的
articles路径,绑定对应的文章列表组件,注意路径名要和代码里跳转的路径完全一致,不要漏写复数s。 - 删掉
app.component.html中静态写死的<app-home></app-home>标签,所有业务组件(包括首页)都应该通过<router-outlet>动态渲染,静态写死会导致不管跳转到哪个页面,首页内容都会一直显示。 - 去掉
<router-outlet>上自定义的name属性,单出口场景用Angular默认的主路由出口即可,命名出口只适合多出口并行渲染的场景(比如侧栏、弹窗同时加载),普通页面跳转不需要用。 - 顺手修正组件名的写法规范:
articleComponent改成大驼峰开头的ArticleComponent,符合Angular组件类名的命名要求。
修正后的路由配置(app-routing.module.ts)
const routes: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'timeline', component: TimelineComponent, }, { path: 'article', component: ArticleComponent, }, { path: 'articles', component: AllarticlesComponent, }, { path: '**', redirectTo: '/' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
修正后的根组件模板(app.component.html)
<div class="app-component"> <nav> <div class="logo"> <img class="home-button" src="./assets/images/3d-printer.png" alt="home button"> </div> <ul class="nav-links"> <li><a routerLink="/" routerLinkActive="active" (click)="toggle()">blog page</a></li> <li><a routerLink="/articles" routerLinkActive="active">all articles</a></li> <li>contact</li> </ul> <div class="logo"> <h4>logo</h4> </div> </nav> <div class="title-container"> <div class="title"> My blog about things </div> </div> <router-outlet></router-outlet> <div class="footer"> <a href="https://www.flaticon.com/free-icons/3d-printing" title="3d printing icons">3d printing icons created by Freepik - Flaticon</a> </div> </div>
注意:永远不要把根组件
AppComponent加入Routes路由配置表,它是承载路由出口的壳容器,不是路由动态加载的业务组件,只要配置到路由中必然会出现组件套娃、重复渲染的问题。
内容的提问来源于stack exchange,提问作者jjhhss
相关产品推荐
相关产品推荐

