繁体   English   中英

Angular 静态 Base URl 和使用 useHash=True 的路由

[英]Angular static Base URl and routing with useHash=True

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

在我的index.html我设置了 base 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#/welcomemy-base之后有一个 # 。

如果我将路由中的代码更改为useHash: false那么 # 在我的基本 URL 之后变为http://localhost:4200/my-base/welcome#/welcome

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

简单总结

主要区别是Server是否容易实现重定向机制

useHash: trueuseHash: false更容易实现


原则

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

当您输入浏览器的网址时

localhost:4200/my-base/welcome/

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


useHash: true ,它使用HashLocationStrategy

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

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

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


参考

Angular 如何使用 PathLocationStrategy(useHash: false) 与服务器端(IIS、Nginx)一起工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM