13

I am using Angular 6, I want my app to have a static base URL for the purpose of reverse proxy configuration.

In my index.html I set 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>

In my app.module.ts I have the routing table configured

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

After I launch the application I noticed the URL is http://localhost:4200/my-base#/welcome, there is a # after my-base.

If I change the code in routing to have useHash: false then the # is after my base URL and becomes http://localhost:4200/my-base/welcome#/welcome

I could not find lots of information what exact the meaning of useHash: false, what is the consequence?

Junaid
  • 4,682
  • 1
  • 34
  • 40
hardywang
  • 4,864
  • 11
  • 65
  • 101

1 Answers1

25

Simple summary

The main difference is whether Server is easy to implement the redirect mechanism

useHash: true is easy to implement than useHash: false


Principle

when you set useHash: false, it's using PathLocationStrategy, It's using HTML5 pushstate that requires server support

When you enter the Url to Browser

localhost:4200/my-base/welcome/

The server needs to redirect localhost:4200/my-base/welcome/ to your index.html


useHash: true, it's using HashLocationStrategy

you need to add # after your base-href('my-base'), the URL is

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

The server directly makes a request to localhost:4200/my-base/ to your index.html, It's easy to implement in server side.


Reference

Angular How to work with Server Side(IIS, Nginx) using PathLocationStrategy(useHash: false)

drac_o
  • 427
  • 5
  • 11
Chunbin Li
  • 2,196
  • 1
  • 17
  • 31