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

Angular路由重定向异常:默认组件未切换至LoginComponent

Angular路由跳转失效的解决方案

你遗漏了两个关键配置步骤:

  • 未在AppModule中注册路由配置
    定义完路由数组后,必须通过RouterModule.forRoot(routes)把路由规则注册到Angular应用里,否则框架无法识别这些路由。修改后的AppModule代码示例:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { RouterModule, Routes } from '@angular/router';
    import { AppComponent } from './app.component';
    import { LoginComponent } from './login/login.component';
    
    const routes: Routes = [
      { path: '', redirectTo: 'login', pathMatch: 'full' },
      { path: 'login', component: LoginComponent, pathMatch: 'full' },
    ];
    
    @NgModule({
      declarations: [AppComponent, LoginComponent],
      imports: [
        BrowserModule,
        RouterModule.forRoot(routes) // 必须添加这行来注册路由
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  • 未在AppComponent模板中添加路由出口
    Angular需要<router-outlet>标签作为路由组件的渲染容器,你得把它加到app.component.html里,否则LoginComponent没有地方显示。修改后的模板示例:

    <!-- app.component.html -->
    <router-outlet></router-outlet>
    

    如果原来的app.component.html有默认的欢迎内容,要么移除,要么保留,路由组件会自动在<router-outlet>的位置渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:02:38