Angular 4 路由无限/#/ in url

Angular 4 routing with infinite /#/ in url

几天以来,我在 Angular CLI 和路由方面遇到了这个问题。 如果您指向确切的 url,它似乎工作正常。 当您尝试使用 routerLink 重定向时,它会在 url 中写入无限 /#page。 如果您在索引上并尝试转到有关页面,它会写 http://baseurl/index#/about#/index#/index#/index#/index#/index#/index#/index#/... 并继续直到完成 RAM :D

此问题仅在 "ng serve" 的开发模式下出现(但适用于 hashlocationstrategy)。在生产模式下似乎工作正常。

这里有一些代码。

在index.html

<base href="/">

app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';

import { ConnectionService, ownerEnums, requestIdEnums } from './services/connection.service';
import { AuthService } from './services/auth.service';

import { AboutComponent } from './about/about.component';
import { ConnectComponent } from './connect/connect.component';
import { LayoutComponent } from './layout/layout.component';

import { HeaderComponent } from './layout/header/header.component';
import { BreadcrumbComponent } from './layout/breadcrumb/breadcrumb.component';
import { FooterComponent } from './layout/footer/footer.component';
import { IndexComponent } from './layout/index/index.component';

@NgModule({
  imports: [
    RouterModule.forRoot([
    { path: '', redirectTo: '/index', pathMatch: 'full' },
    { path: 'about', component: AboutComponent },
    { path: 'connect', component: ConnectComponent },
    { path: 'index', component: LayoutComponent }
    ]),
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [
    AppComponent,
    AboutComponent,
    ConnectComponent,
    LayoutComponent,
    HeaderComponent,
    BreadcrumbComponent,
    FooterComponent,
    IndexComponent
  ],
  providers: [ ConnectionService, AuthService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

在关于页面中使用 routerLink 锚定

    <div>
        <a class="navbar-brand" [routerLink]="['/about']"><i class="fa fa-info"></i></a>
        <a class="navbar-brand" [routerLink]="['/connect']"><i class="fa fa-plug"></i></a>
    </div>

将您的路由器模块更改为

{ path: 'about', component: AboutComponent },
{ path: 'connect', component: ConnectComponent },
{ path: 'index', component: LayoutComponent },
{ path: '', redirectTo: 'index', pathMatch: 'full'},
{path:'**',redirectTo:'index',pathMatch:'full'}

在路由模块的@NgMoudle 中添加 {useHash:true} 选项。这将解决问题,但我不完全明白为什么。该选项旨在与旧浏览器兼容,但我使用的是最新的 Chrome。我在同一台 PC 上使用相同的浏览器编写了其他 angular 项目,但没有出现此问题,我的代码出现问题似乎是相同的。我写这篇文章不是作为解决方案,但鉴于没有人回答过这个问题,我希望我的回答可以作为 'clue' 比我更好的人来解释它发生了什么以及为什么

@NgModule({
imports:[RouterModule.forRoot(appRoutes, {useHash: true})], 
exports:[RouterModule]
})