角度静态基本 URl 和 userHash=True 的路由



我正在使用 Angular 6,我希望我的应用程序有一个静态的基本 URL,以便进行反向代理配置。

在我的index.html中,我设置了基本网址

<!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 { }

启动应用程序后,我注意到URLhttp://localhost:4200/my-base#/welcomemy-base后有一个#。

如果我将路由中的代码更改为具有useHash: false则#位于我的基本URL之后并变为http://localhost:4200/my-base/welcome#/welcome

我找不到很多信息,useHash: false的确切含义是什么,后果是什么?

简单总结

主要区别在于服务器是否易于实现重定向机制

useHash: trueuseHash: false更容易实现

<小时 />

原理

当你设置useHash: false时,它使用的是PathLocationStrategy,它使用的是需要服务器支持的HTML5 pushstate

当您输入浏览器的网址时

localhost:4200/my-base/welcome/

服务器需要将localhost:4200/my-base/welcome/重定向到您的索引.html


useHash: true,它使用的是HashLocationStrategy

您需要在 base-href('my-base'( 之后添加#,URL 是

localhost:4200/my-base/#/welcome/

服务器直接向localhost:4200/my-base/发出请求到你的索引.html,在服务器端很容易实现。

<小时 />

参考

Angular 如何使用 PathLocationStrategy(useHash: false( 与服务器端(IIS, Nginx(

一起工作
  • 将 Angular 应用程序部署到 IIS
  • Nginx 和 Angular URL 路由

最新更新