Angular — The hash(#) trap

Houssene Dao
2 min readJan 31, 2019

--

For developers who use the SPA, it may be common to notice a hash (#) at the URL. Since the new version of Angular it is possible to work on an application without seeing this famous # character in the URL. Is that normal? For most people it seems to be pretty cool, actually it is, it’s cool, because we find the usual syntax of URLs.

Is that normal?

Yes, it is normal to work on an Angular application without seeing the hash (#). It still exists only that it is disabled by default on the different versions of Angular.

A trap!

Amazing, isn’t it? Yes, a trap the problem arises once the application is deployed on a production server. You think, but if it works locally in principle no problem for a production environment, unfortunately not usually in a production environment when you try to navigate between pages or even update the entry page we have an error of type 404page not found.

The solution

The Angular team proposes to use of Angular Universal. If you want to use a simple and easy solution, I recommend the use of hash.

How to activate the hash?

To activate the hash we have two methods

First method

In app.module.ts

  • We import
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
  • Then, we add this line in the NgModule as provider
{provide: LocationStrategy, useClass: HashLocationStrategy}

Example (app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
bootstrap: [AppComponent],
})
export class AppModule {}

Second method

We use RouterModule.forRoot with the argument {useHash: true}.

Example: (app-routing.module.ts)

import { NgModule } from '@angular/core';
...
const routes: Routes = [//routes in here];@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes, { useHash: true })
],
bootstrap: [AppComponent]
})
export class AppModule { }

Conclusion

And that’s all, if you have trouble with the activation of the hash just leave a comment, I’d be happy to answer you.

Thank you!

--

--