【问题标题】:Angular routing always redirect to home page角度路由总是重定向到主页
【发布时间】:2018-02-11 01:46:42
【问题描述】:

我在这个看似简单的问题上花费了太多时间。我有一条路线,page2 定义如下:

// app.module.ts
import { Page2Component } from './page2/page2.component';

@NgModule({
  declarations: [
    AppComponent,
    Page2Component
  ],
  imports: [
    BrowserModule, RouterModule.forRoot([
      { path: 'page2', component: Page2Component },
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我在index.html 中检查了<base href="/">。但是,当我手动输入http://localhost:4200/page2 时,我总是被重定向回主页(在app.component 中定义)。

我一遍又一遍地查看快速入门指南,但不知道为什么。我的路由定义有什么问题?


编辑:我用一个全新的应用程序(通过ng new test-app)和新的page2 组件(ng generate component page2)对其进行了测试。还是同样的问题。我现在更困惑了。

【问题讨论】:

  • 这是ng serve 还是试图托管ng build 的内容?如果您遇到ng serve 的这个问题,请发布您的完整 app.module.ts。如果您尝试托管 dist 版本,请在下面查看我的答案(更新)。
  • 显示所有路线

标签: angular routing


【解决方案1】:

我找到了另一个帖子 Angular2 - app.module routing: blank path not redirecting to component 来解决我的问题。当我从:

export const ROUTES: Routes = [
  { path: '', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent  }
];

export const ROUTES: Routes = [
  { path: 'dashboard', component: DashboardComponent  },
  { path: '', component: LoginComponent }
];

它开始起作用了。

【讨论】:

    【解决方案2】:

    我猜你错过了将<router-outlet></router-outlet> 添加到你的 App.component.html,

    将它添加到您要加载路由组件的 app.component.html 中

    【讨论】:

    • 这个。简直不敢相信这么简单!
    • 我也有同样的问题。我的 app.component.html 中已经有 <router-outlet> 选择器,但是我仍然遇到同样的问题。我还能做什么?
    • @LostAtSea 问题可能出在您的href 属性上,如果它链接到“”,那么无论您的“routerLink”的值是多少,它很可能会回家。
    【解决方案3】:

    最可能的问题是您没有导入RouterModule 或Routes。

    一定要包括:

    import { RouterModule, Routes } from '@angular/router';
    

    编辑:在上一个答案中,我包括了一个可能的其他问题,但不需要输入 Routes。如果你已经包含了这两个,这可能是一个与浏览器相关的错误(这发生在没有启用路由参数转发的 apache 服务器上)。如果您尝试ng build 并使用 dist 文件,则需要启用参数转发。请参阅 github 上的this post。您应该仍然可以使用 ng serve 在本地运行您的应用程序而不会出现问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多