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?

1

1 Answer 1

24

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.