当我们在 Angular 应用中使用 HTML5 样式的 URL 的时候,就会碰到 Angular 应用的部署路由位置问题。在部署之后,我们的 URL 会变得更长,这会导致我们的路由出现问题。为了解决这个问题,我们需要在 app.module.ts 文件中添加一个配置选项,代码如下:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
], { useHash: true })
],
declarations: [ AppComponent, HomeComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
在上述代码中,我们通过设置 useHash 为 true,来帮助我们解决 Angular 应用的路由位置问题。这个配置选项会把我们的 URL 变成带有 # 符号的 URL,从而避免了路由位置问题。