【问题标题】:Angular4 refresh page repeats page in urlAngular4刷新页面在url中重复页面
【发布时间】:2018-03-31 03:04:32
【问题描述】:

我是 Angular 新手,构建了一个简单的单页机。我有路由器设置,以便空 url 重定向到仪表板组件。因此localhost:4200 将自动路由到localhost:4200/dashboard Perfect。

但是,如果我单击刷新按钮,则会将另一个仪表板附加到 url,奇怪的是页面实际上加载得很好。 localhost:4200/dashboard/dashboard

如果我再次点击刷新,它会在 url 中添加另一个仪表板,现在它不会加载

localhost:4200/dashboard/dashboard/dashboard

问题是,为什么每次刷新页面时它都会在我的网址中添加“/dashboard”?

这里是 routing.module.ts

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

import { DashboardComponent } from '../_feature/iacuc/dashboard.component';

const appRoutes: Routes = [
    { path: '', redirectTo: 'dashboard', pathMatch: 'prefix' },
    { path: 'dashboard', component: DashboardComponent }

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const Routing = RouterModule.forRoot(appRoutes);

这是我的 index.html

<!DOCTYPE html>
<html>
<head>
    <base href="/" >
    <title>Angular 2 JWT Authentication Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- bootstrap css -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

    <!-- application css -->
    <link href="app.css" rel="stylesheet" />

    <!-- polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function (err) { console.error(err); });
    </script>
</head>
<body>
    <app>Loading...</app>
</body>
</html>

其余代码是您在介绍性示例中看到的样板代码,但如果有帮助,我可以展示更多代码。

谢谢。

【问题讨论】:

  • pathMatch: 'prefix' 改为pathMatch: 'full'
  • 关键字字面意思是'前缀'哈哈
  • 'full' 也不起作用。
  • 如果您在index.htmlhead 部分的顶部没有基本href,请尝试将其添加为:&lt;base href="/"&gt; (angular.io/guide/router#base-href)
  • 我也有那个。我更新了我的问题以显示我的 index.html。我想我可能只是下载 Angular.io hero 应用程序并用我的页面替换他们的页面,而不是从头开始并试图在我的代码中找到这个神秘的错误。

标签: angular routing


【解决方案1】:

需要使用 pathMatch: 'full' 而不是 pathMatch: 'prefix'

在这里阅读:https://angular.io/api/router/Routes

【讨论】:

  • 除了按照您的建议将其更改为 pathMatch: 'full' 之外,还需要将路由从使用字符串更改为使用组件名称。它将该字符串附加到根 url。正确路线:{ path: '', component: DashboardComponent, pathMatch: 'full' }
  • 我尝试添加 pathMatch: 'full',但仍然遇到同样的问题,它在重新加载页面时在 URL 中添加相同的页面名称。还有其他解决方案吗?,我在使用命令ng build --prod --aot --base-href;生成构建后遇到了这个问题
猜你喜欢
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 2019-02-24
  • 1970-01-01
  • 2019-10-14
  • 2016-09-04
  • 1970-01-01
相关资源
最近更新 更多