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

标签 angular angular-ui-router

我正在使用 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#/welcomemy-base 后面有一个 # .

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

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

最佳答案

简单总结

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

useHash: trueuseHash: 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/

相关文章:

javascript - Angular 2 应用程序组件未加载

javascript - 如何调用 Angular 组件中 asset 文件夹下单独文件中的外部 Javascript 函数?

javascript - 当 Angular Service 将动态 URL 作为常量时,如何处理?

angularjs - 转换拒绝 Angular UI 路由器

javascript - Angular JS |刷新浏览器时,angularjs 模板会在安全上下文之前加载。如何阻止它?

javascript - <a> 点击不工作但 href 是正确的并且工作

Angular:将 XML 转换为 JSON

javascript - 为什么我的构造函数参数私有(private)类成员在运行时未定义?

javascript - 数组推送的 Angular2 刷新 View

angular - 代理配置在 Angular 6 中不起作用