【问题标题】:Angular 8 Routing: Changing URL doesn't navigate to expected pageAngular 8 路由:更改 URL 无法导航到预期页面
【发布时间】:2020-05-13 05:17:10
【问题描述】:

我正在创建一个包含两个组件的简单 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 谷歌浏览器

【问题讨论】:

  • 您在浏览器控制台中看到任何错误吗?
  • 没有。只有普通的 Angular 东西
  • 你的 index.html 头中添加了<base href="/"> 吗?
  • 是的。我确实在 index.html
  • 您的应用路由模块看起来如何?请分享更多细节。

标签: angular browser url-routing


【解决方案1】:

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

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

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

  2. 未将 AppRoutingModule 导入您的 AppModule

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

我在 cmets 中看到您的 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 中重新创建您的应用并发布链接。

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2020-08-26
    • 2019-07-27
    相关资源
    最近更新 更多