Angular 8 路由:更改 URL 不会导航到预期页面

Angular 8 Routing: Changing URL doesn't navigate to expected page

我正在创建一个包含两个组件的简单 Angular 项目:homesubmit。我的 app-routing.module.ts 看起来像这样:

import { NgModule } from '@angular/core';
import { Routes, RouterModule, ActivatedRoute } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { SubmitComponent } from './submit/submit.component';


const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'submit', component: SubmitComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule { }

在我的浏览器中,如果我将路径更改为 /submit,页面看起来会重新加载,然后默认返回 /home。我已经尝试将 path: '' 更改为 path: '**'。它不会导航到 submit 组件。任何想法我做错了什么?

Angular 8.2.14 GoogleChrome

您的路由配置没有任何问题。我们没有足够的信息来帮助您查明您的问题。

当有人问我这个问题时,通常是以下问题之一:

  1. 您的 index.html head 元素中缺少 <base href="/">

  2. 没有将 AppRoutingModule 导入您的 AppModule

  3. 失踪 <router-outlet></router-outlet> 父组件中的元素

我在评论中看到您的 index.html 文件中有 <base href="/">,所以我们暂时忘记那个。

从这里开始:

检查以确保您在 App.Module.ts 文件中导入 AppRoutingModule

如果这不是问题,请确保您的父组件中有一个 <router-outlet></router-outlet> 元素(根据您的应用程序的简单性,可能是您的 app.component.html)。 Angular 路由器在您的路由中搜索与 URI 匹配的路由,并将路由配置中指定的组件实例注入组件树中最近的 router-outlet 中。换句话说,如果没有 router-outlet,Angular 路由器不知道在哪里呈现您在路由配置中指定的组件。

如果这些都不能解决您的问题,请尝试发布更多信息以便我们进一步提供帮助。至少查看 app.module.ts 和 app.component.html 文件会很有帮助。或者,尝试在 stackblitz 中重新创建您的应用并发布 link.