使用 Angular 10 + AWS S3 + Cloudfront 路由时,可以使用 HTML5 的 history API 实现不带哈希的路由,解决路由带有哈希的问题。具体实现步骤如下:
1.首先在 app.module.ts 文件中 import BrowserModule 和 RouterModule,并配置路由:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'page1', component: Page1Component },
{ path: 'page2', component: Page2Component },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
Page1Component,
Page2Component,
PageNotFoundComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, { useHash: false })
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
其中,useHash 为 false,表示路由不带哈希。
2.在 index.html 文件中增加以下代码:
其中,
3.使用 npm install --save-dev @types/node 安装 node 类型。
4.在 app.component.ts 文件中添加以下代码:
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';