我正在使用 Angular 6,我希望我的应用程序具有静态基本 URL,以便进行反向代理配置。
在我的 index.html
中,我设置了基本 Url
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>APM</title>
<base href="/my-base">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<pm-root></pm-root>
</body>
</html>
在我的 app.module.ts
中,我配置了路由表
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { WelcomeComponent } from './home/welcome.component';
@NgModule({
declarations: [
AppComponent,
WelcomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: "welcome", component: WelcomeComponent },
{ path: "", redirectTo: "welcome", pathMatch: "full" },
{ path: "**", redirectTo: "welcome", pathMatch: "full" }
], { useHash: true })
],
bootstrap: [AppComponent]
})
export class AppModule { }
启动应用程序后,我注意到 URL 是 http://localhost:4200/my-base#/welcome
,my-base
后面有一个 # .
如果我将路由中的代码更改为 useHash: false
,则 # 位于我的基本 URL 之后,并变为 http://localhost:4200/my-base/welcome#/欢迎
我找不到很多信息useHash: false
的确切含义,结果是什么?
最佳答案
简单总结
主要区别是Server是否容易实现重定向机制
useHash: true
比 useHash: false
更容易实现
原理
当您设置useHash: false
时,它使用PathLocationStrategy,它使用需要服务器支持的HTML5 Pushstate
当您在浏览器中输入 URL 时
localhost:4200/my-base/welcome/
服务器需要将localhost:4200/my-base/welcome/重定向到您的index.html
<小时/>useHash: true
,它使用HashLocationStrategy
您需要在base-href('my-base')后添加#
,网址为
localhost:4200/my-base/#/welcome/
服务器直接向localhost:4200/my-base/发出请求到你的index.html,在服务器端很容易实现。
<小时/>引用
Angular 如何使用 PathLocationStrategy(useHash: false) 与服务器端(IIS、Nginx)合作
关于Angular 静态 Base URl 和 useHash=True 的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52416210/